使用内容丰富的 cms 时定义数组索引时无法显示数据
Unable to display data when define array index when using contentful cms
在内容丰富的 cms 中使用数组索引时无法获取数据
constructor() {
super();
this.state = {
partners: [],
}
}
client = contentful.createClient({
space: process.env.REACT_APP_CONTENTFUL_SPACE_ID,
accessToken: process.env.REACT_APP_CONTENTFUL_ACCESS_TOKEN
})
componentDidMount() {
this.client.getEntries({
'content_type': 'partnersCollection',
'order': 'sys.createdAt',
})
.then(response => {
this.setState({
partners: response.items
})
})
.catch(console.error);
}
render(){
console.log("SIDE BAR RESULT: ", this.state.partners)
console.log(this.state.partners[0])
return null;
}
Console.log("SIDE BAR RESULT: ", this.state.partners)
将显示来自 contentful cms 的所有结果。当与数组索引示例一起使用时 this.state.partners[0].fields
将出现错误
Cannot read property 'fields' of undefined
有谁知道为什么数组索引会导致错误消息?
在初始状态 - this.state.partners
是空数组,因此找到 this.state.partners[0].fields
会给出错误
你需要检查渲染
if(this.state.partners.length > 0) {
this.state.partners[0].fields
}
一旦 promise 被解析,它将在 componentDidMount()
中设置 state.partners
,render()
将自行更新。
在内容丰富的 cms 中使用数组索引时无法获取数据
constructor() {
super();
this.state = {
partners: [],
}
}
client = contentful.createClient({
space: process.env.REACT_APP_CONTENTFUL_SPACE_ID,
accessToken: process.env.REACT_APP_CONTENTFUL_ACCESS_TOKEN
})
componentDidMount() {
this.client.getEntries({
'content_type': 'partnersCollection',
'order': 'sys.createdAt',
})
.then(response => {
this.setState({
partners: response.items
})
})
.catch(console.error);
}
render(){
console.log("SIDE BAR RESULT: ", this.state.partners)
console.log(this.state.partners[0])
return null;
}
Console.log("SIDE BAR RESULT: ", this.state.partners)
将显示来自 contentful cms 的所有结果。当与数组索引示例一起使用时 this.state.partners[0].fields
将出现错误
Cannot read property 'fields' of undefined
有谁知道为什么数组索引会导致错误消息?
在初始状态 - this.state.partners
是空数组,因此找到 this.state.partners[0].fields
会给出错误
你需要检查渲染
if(this.state.partners.length > 0) {
this.state.partners[0].fields
}
一旦 promise 被解析,它将在 componentDidMount()
中设置 state.partners
,render()
将自行更新。