我有两个组件,父组件应用程序和子组件SearchBar,我希望SearchBar保持自己的状态,在更新其状态之后,调用父组件提供的函数作为将更新父状态的支柱。
所以在我的SearchBar组件上
onSearchChange(event) {
.
.
.
this.setState({ searchTerm });
}然后
componentDidUpdate(){
this.props.onSearchChange(this.state.searchTerm)
}以及父组件上的
onSearchChange(searchTerm){
this.setState({searchTerm});
}
render() {
return (
<div className="App">
<div>
<SearchBar onSearchChange={this.onSearchChange}/>
</div>
.
.
.
</div>
);
}但这会导致无限循环,其中调用搜索栏的componentDidUpdate,调用其父onSearchChange更新父状态,然后调用搜索栏的componentDidUpdate,再次调用componentDidUpdate,以此类推。
如果我在setState中使用回调而不是componentDidUpdate来更新它的父状态,它就能正常工作,但我只是不明白为什么SearchBar它的更新支持它的常量。
发布于 2018-03-19 15:15:53
componentDidUpdate提供了两个参数prevProps和prevState,使用它您可以检查实际道具或状态是否已经更改,然后对当前状态/道具进行更改。例如:
componentDidUpdate(prevProps, prevState){
if(prevState.searchTerm !== this.state.searchTerm) {
this.props.onSearchChange(this.state.searchTerm)
}
}https://stackoverflow.com/questions/49365944
复制相似问题