我有一个状态变量dataSource
,其中包含一些数据。
在父组件中,我有以下内容:
updateFeed = newItem => {
this.setState({ dataSource: this.state.dataSource.data.unshift(newItem) })
console.log(this.state.dataSource.data)
}
render() {
console.log(this.state.dataSource.data)
return (
<React.Fragment>
<Header />
<Route
path="/"
exact
component={props => (
<Feed {...props} feedData={this.state.dataSource.data} updateFeed={this.updateFeed} />
)}
/>
<Route path="/profile/:id" exact component={props => <Profile {...props} />} />
</React.Fragment>
)
}
updateFeed
从子组件中调用。
onSubmit = () => {
const newPost = newData // some new data
this.props.updateFeed(newPost)
}
updateFeed
函数在提交时执行,console.log
提供更新的数据。但在渲染函数内部,this.state.dataSource.data
是未定义
。我在这里缺少什么?
最佳答案
您在 setState 调用中执行了 dataSource: dataSource.data
,因此渲染方法中的 dataSource.data
实际上会访问 dataSource.data.data
code> 这可能是未定义的。可以将 updatedFeed
更改为:
updateFeed = newItem => {
this.setState(prev => ({
dataSource: {
...prev.dataSource,
data: prev.dataSource.data.concat(newItem)
}
}));
}
这确保了纯净的状态。
关于javascript - React 状态变量在 render 方法中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49989527/