我有两个组件,用户可以在其中将图像或 gif 附加到帖子中。每当单击图像时,都会弹出一个模态框,我想将数据传递回模态框,以便显示单击的图像。
我做了一个生命周期钩子(Hook),这样我就可以检查是否正在发送 props,然后像这样在我的子组件中设置状态:
componentWillReceiveProps(){
if(this.props.modalImageData){
this.setState({imageData: this.props.modalImageData})
}
}
这工作正常,但我在正确传递状态时遇到问题。
我创建了一个处理程序,我将点击图像的图像数据传递到一个处理程序中,该处理程序为名为 imageModalData 的属性设置状态,我将其传递给 CreateGif 组件:
showModalSpeceficHandler = (event, image) =>{
//console.log(event.target.value);
console.log('image data is ' + image)
this.setState({imageModalData: image})
console.log('modal image data is ' +
this.state.imageModalData)
this.showModalHandler()
}
这里,当我第一次控制台记录图像时遇到问题,该图像被传递到函数中,它是正确的,但之后,当我控制台记录 imageModalData 的状态时,它显示随机图片。
之后,随机图片被传递回子组件,这是不希望的,我做错了什么,因为状态没有正确放置
Modal show={this.state.showModal} modalClosed={this.showModalHandler}>
<CreateGif onSelectUrl={this.addedImageHandler} onSelectFile={this.addFileDataHandler} modalImageData={this.state.imageModalData}/* this is where the data is passed back down */ />
最佳答案
看看 docs for setState
:
Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
如果您需要确保在触发某些操作(如呈现模态)之前已应用更新,您可以使用 setState(updater, callback)
形式:
this.setState(
// updater function, returning a state update
state => ({imageModalData: image}),
// callback function, executed after update is applied
() => this.showModalHandler()
);
关于javascript - Setstate 未正确执行。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53553060/