Я новичок в React, и мне трудно, например, отобразить первый элемент массива.
Я получаю TypeError: Cannot read property 'title' of undefined, даже если он работает с console.info. Вот код:
constructor() {
super()
this.state = {
posts: []
}
this.componentDidMount = this.componentDidMount.bind(this)
}
async componentDidMount() {
const url = "https://jsonplaceholder.typicode.com/posts";
const response = await fetch(url);
const data = await response.json();
this.setState({
posts: data
})
console.info(data); //working
console.info(this.state.posts) //working
console.info(this.state.posts[0].title) //working
}
render() {
return (
<div className = "head-title"> { this.state.posts[0].title } </div>
<div className = "head-body"> { this.state.posts[0].body} </div>
)
}
Что я делаю неправильно ?





Ваш компонент попытается выполнить рендеринг this.state.posts[0].title, пока запрос еще не завершен, и, таким образом, выдаст ошибку.
Добавьте проверку, чтобы убедиться, что ваши данные существуют, например, так:
render() {
return (
<div className = "head-title"> { (this.state.posts.length > 0) ? this.state.posts[0].title : null } </div>
<div className = "head-body"> { (this.state.posts.length > 0) ? this.state.posts[0].body : null} </div>
)
}
Вы можете сделать так. В дополнение к моему ответу:
class test extends Component{
constructor() {
super()
this.state = {
posts: [],
loading :true
}
this.componentDidMount = this.componentDidMount.bind(this)
}
async componentDidMount() {
const url = "https://jsonplaceholder.typicode.com/posts";
const response = await fetch(url);
const data = await response.json();
this.setState({
posts: data,
loading:false
})
console.info(data); //working
console.info(this.state.posts) //working
console.info(this.state.posts[0].title) //working
}
}
render() {
if (this.state.loading) return null;//Dont render component
//or add ternary condition
return (
<div className = "head-title"> { this.state.posts[0].title } </div>
<div className = "head-body"> { this.state.posts[0].body} </div>
)
}
}
Спасибо большое, так и было!
Это потому, что он сначала отображается, а затем ваши новые данные заполняются для состояния. Как вызов setState после успешного ответа. вам нужно добавить некоторый флаг, например загрузку, чтобы он не отображал этот jsx до тех пор, пока не будут установлены значения API