我有三个组成部分:
我遇到的问题是每个组件的状态总是落后一步。我意识到这是因为setState是异步的,但是我不确定解决该问题的最佳方法是什么。我已经阅读了一些可能的解决方案,但是我不确定如何在我的设置中最好地实现它们。有人可以建议吗?
这里是PageBuilder(为了清楚起见,我将其缩减):
constructor(props){
super(props);
this.state = {
pageTitle: '', pageDesc:'', items: [], id:''
};
}
updateTitle = (e) => {
this.setState({pageTitle: e.target.value});
}
updateDesc = (e) => {
this.setState({pageDesc: e.target.value});
}
addNewPage = () => {
let info = {...this.state};
this.props.callBack(info);
}
render() {
return (
<input className="pageTitleField" type="text" placeholder="Page Title"
value={this.state.pageTitle} onChange={this.updateTitle}></input>
<textarea className="pageDescField" placeholder="Page description..."
onChange={this.updateDesc}></textarea>
<button onClick={this.addNewPage}>New Page</button>
)
}
PageUpdater:
export class PageUpdater extends React.Component{
constructor(props){
super(props);
this.state={
data: ''
}
}
updatePageList = (pageAdded) =>{
this.setState({data:pageAdded});
console.log(this.state)
}
render(){
return(
<div>
<PageBuilder callBack={this.updatePageList} />
<PageList addToList={this.state.data} />
</div>
)}}
PageList:
export class PageList extends React.Component{
constructor(props){
super(props);
this.state = {pages:''}
}
componentWillReceiveProps(props) {
this.setState({pages: [...this.state.pages, this.props.addToList]})
}
getPages = () => {
var pages = []
for(var key in this.state.pages){
pages.push(this.state.pages[key].pageTitle)}
return pages // Return an array with the names
}
render(){
return(
<div>
{this.getPages().map((page, index) => <li key={index}>{page}
</li>)}
</div>
)}}
答案 0 :(得分:1)
componentWillReceiveProps this.props
内指的是道具的先前版本。但是,您需要使用最新版本的道具。
代替
componentWillReceiveProps(props) {
this.setState({pages: [...this.state.pages, this.props.addToList]})
}
您应该写
componentWillReceiveProps(nextProps) {
this.setState({pages: [...this.state.pages, nextProps.addToList]}) // notice the difference this.props vs nextProps
}