我是React的新手,但是我很难显示例如数组的第一个元素。
即使使用console.log,我也得到了TypeError: Cannot read property 'title' of undefined
。这是代码:
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.log(data); //working
console.log(this.state.posts) //working
console.log(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>
)
}
我在做什么错了?
答案 0 :(得分:2)
您可以这样做。除了我的答案:
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.log(data); //working
console.log(this.state.posts) //working
console.log(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>
)
}
}
答案 1 :(得分:0)
您的组件将在请求仍未完成时尝试呈现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>
)
}