this.props.allStagesData
来自父组件中的 AJAX 请求。如果我注释掉 console.log('stageID', currentStage._id);
,则在我最终获取数据之前,该组件当前会加载 3 次。当该日志取消注释时,它会抛出 Uncaught TypeError: Cannot read property '_id' of undefined
,因为我还没有数据。
如何在初始渲染时加载此数据?
export default class NavMain extends React.Component {
constructor(props) {
super(props);
this.state = {
stagesData: []
}
}
componentWillMount() {
var stagesData = this.props.allStagesData;
this.setState({
stagesData: stagesData
})
}
render() {
var stagesData = this.state.stagesData,
currentStage = _.find(stagesData, {'_status': "open"});
console.log('this.props.allStagesData', this.props.allStagesData);
console.log('this.state.stagesData', stagesData);
console.log('currentStage', currentStage);
console.log('stageID', currentStage._id);
return (
...
)
}
}
(忽略图像中的两个错误,它们是无关的。)
最佳答案
在数据到达之前,您可以简单地返回其他内容,或者null
。尝试将 if(this.state.stagesData.length === 0) return null
添加到渲染函数的第一行。这样,在数据实际存在之前,它不会显示。
编辑:为了回答您的问题,数据不能在第一次渲染时出现。更好的方法是返回包含除数据之外的所有内容的 HTML,或者如上所述简单地返回 null,直到请求完成。如果需要,您还可以渲染加载指示器!
关于reactjs - react : Getting props to load on initial render,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39497329/