javascript - Setstate 未正确执行。

标签 javascript reactjs state

我有两个组件,用户可以在其中将图像或 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/

相关文章:

javascript - 向对象添加原型(prototype)方法

javascript - 在单个 div 上启用滚动?

jquery - 从 create-react-app 项目中排除 Webpack 的依赖项

javascript - 从孙子中的 onClick 更新 React 祖 parent 状态

javascript - 如何改变react中的状态值

angular - Redux 中的状态是什么?

javascript - html输入框 "value"属性内的if语句

javascript - 使用剑道创建一个单选按钮自定义(更改背景颜色)

javascript - map is not a function 在 REACT 中对数组使用 push 后出现错误

javascript - 在react-redux实现中mapStateToProps如何接收更新后的状态