【问题标题】:setState() wiith Redux in React [duplicate]在 React 中使用 Redux 的 setState() [重复]
【发布时间】:2019-06-03 04:47:45
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: redux react-redux


    【解决方案1】:
     if (nextProps.uploadImage) {
        this.setState({ photostatus: 'image' 
      },()=>console.log(this.state.photostatus))
     }
    

    通过改变这种方式检查

    【讨论】:

    • 感谢@Kishan Jaiswal 的解决方案。我知道你的解决方案。但是当我调用它时,我的组件需要photostatus: 'image'。 setState 回调在这里不起作用。
    • stackoverflow.com/questions/39171184/… 请阅读此内容以及关于 componentWillReceiveProps 的 llifecycle
    • componentWillReceiveProps 渲染不同于所有其他生命周期
    • 感谢@Kishan Jaiswal 的解决方案。我应该在这里做什么?在这种情况下你有什么看法?我应该使用 componentDidUpdate 而不是 componentWillReceiveProps 吗?谢谢。
    • 我的问题在this.setState()。如何设置 photostatus 的状态?谢谢。
    【解决方案2】:
    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
            }
            );
        }
    }
    

    【讨论】:

    • 感谢@Anita 的解决方案。我知道你的解决方案。但是当我调用它时,我的组件需要photostatus: 'image'。 setState 回调在这里不起作用。
    猜你喜欢
    • 2017-01-04
    • 1970-01-01
    • 2017-08-09
    • 2023-01-22
    • 2022-11-28
    • 2017-04-21
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多