setState()和Redux在React中

时间:2019-06-03 04:47:45

标签: redux react-redux

我正在用React学习Redux。我正在使用dispatch,如下所示

this.props.dispatch(uploadImage(formData, config, element_id));

我的mapStateToProps如下所示

const mapStateToProps = state => ({
    uploadImage: state.addressReducer.uploadImage
});

export default connect(mapStateToProps)(ModalElement);

我想得到如下输出

componentWillReceiveProps(nextProps) {
    if (nextProps.uploadImage) {
        this.setState({ photostatus: 'image' });
        console.log(this.state.photostatus)  // getting wrong output, not `image`
    }
}

这是我的仓库https://github.com/afoysal/mern/blob/master/client/src/components/ModalElement.js

2 个答案:

答案 0 :(得分:1)

 if (nextProps.uploadImage) {
    this.setState({ photostatus: 'image' 
  },()=>console.log(this.state.photostatus))
 }

通过这种方式进行检查

答案 1 :(得分:1)

componentWillReceiveProps(nextProps) {
    if (nextProps.uploadImage) {
        this.setState({ photostatus: 'image' }, () =>{
          console.log(this.state.photostatus)  // this.setState is asynchronous so you won't find the changes immediately
        }
        );
    }
}