【发布时间】:2018-08-28 04:32:02
【问题描述】:
我有两个组件,父组件 App 和子组件 SearchBar,我希望 SearchBar 保持自己的状态,并在更新其状态后调用其父级给定的函数作为将更新其父级状态的 prop。
所以在我的 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>
);
}
但这会导致一个无限循环,其中 SearchBar 的 componentDidUpdate 被调用,它调用其父 onSearchChange 来更新父状态,但随后 SearchBar 的 componentDidUpdate 再次被调用,依此类推。
如果我在 setState 中使用回调而不是 componentDidUpdate 来更新其父状态,它可以正常工作,但我只是不明白为什么 SearchBar 如果它的 prop 是常量,它会更新。
【问题讨论】:
-
使用 setState 回调方法:
this.setState({ searchTerm }, () => this.props.onSearchChange(this.state.searchTerm));. -
当然可以,但我的问题是,如果它的 prop 没有改变,为什么 componentDidUpdate 会再次被调用。
-
该问题有很多答案,请查看stackoverflow results :)
标签: javascript reactjs