我有一个“主”组件,它有一个子组件,它有一个搜索表单。
尽管还没有任何效果,但我想确保我的主要组件获取我在搜索栏中输入的值。但是,我注意到我的主组件比子组件晚一步获取数据。
主要组件
export default class MainComponent extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {input: null};
}
handleFilterInput(value) {
this.setState({input: value});
console.log(this.state.input);
}
render() {
return (
<div>
<ChilComponent handleFilterInput={this.handleFilterInput.bind(this)}/>
// Rest of the component
)
}
}
子组件
export default class ChildComponent extends React.Component {
onFieldChange(event) {
console.log(event.target.value);
this.props.handleFilterInput(event.target.value);
}
render() {
return (
<div>
<input
label="Search"
margin="normal"
name="search"
onChange={this.onFieldChange.bind(this)}
type="text"
/>
</div>
)
}
}
可以看到,主组件和主组件中都有一个console.log
。假设我想输入“article”,结果如下:
child_component.js:21 a
main.js:116 *null*
child_component.js:21 ar
main.js:116 a
child_component.js:21 art
main.js:116 ar
child_component.js:21 arti
main.js:116 art
child_component.js:21 artic
main.js:116 arti
child_component.js:21 articl
main.js:116 artic
child_component.js:21 article
main.js:116 articl
发生了什么、为什么以及如何解决?
提前谢谢
最佳答案
setState()
是异步的,因此当您在调用 this.setState()< 后尝试立即
,您的状态尚未更新。console.log(this.state.input)
时
在 ChildComponent
中,您直接记录来自实时发生的事件的数据。
如果您希望主组件记录相同的内容,您可以这样做:
handleFilterInput(value) {
this.setState({input: value}, () => console.log(this.state.input));
}
setState()
的第二个参数是一个在状态更新时执行的函数。
您还可以在主组件中使用componentDidUpdate(prevProps, prevState)
:
componentDidUpdate() {
console.log(this.state.input);
}
关于javascript - 主组件比其子组件晚一步获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48798473/