首页 > 解决方案 > React - ComponentDidMount 没有从 Redux 状态中获取价值

问题描述

我正在正确更新 Redux 状态。这是 Redux 的状态updateNeeded(在这种情况下是真的)。 在此处输入图像描述

我正在控制台记录该值this.props.mandatory_fields.updateNeeded,但它始终是我设置的初始状态。它没有从 Redux 状态更新。下面是我进行 api 调用的代码。

class CompleteProfile extends Component {
  state = {
    completeProfile: false,
  }

  componentDidMount = () => {
    let { dispatch, session } = this.props
    dispatch(getMandatoryFields(session.username))
    console.log(
      'this.props.mandatory_fields.updateNeeded -- ' +
        this.props.mandatory_fields.updateNeeded
    )
    if (this.props.mandatory_fields.updateNeeded !== false) {
      this.setState({
        completeProfile: this.props.mandatory_fields.updateNeeded,
      })
    }
  }
...
...
....
const mapStateToProps = state => ({
  mandatory_fields: state.User.mandatory_fields,
  session: state.User.session,
})

export default connect(mapStateToProps)(CompleteProfile)

控制台日志结果是

this.props.mandatory_fields.updateNeeded -- false

它应该true如上面的 Redux 状态图所示。我错过了什么?

标签: reactjsredux

解决方案


您必须签this.props.mandatory_fields.updateNeededcomponentDidUpdate挂钩。更改 Redux 状态后,组件将被更新。因此,您必须在致电调度后立即办理登机手续propscomponentDidUpdate不是立即办理登机手续。你可以看到我的代码:

componentDidUpdate(prevProps, prevState, snapshot) {
    console.log(
        'this.props.mandatory_fields.updateNeeded -- ' +
        this.props.mandatory_fields.updateNeeded
    )
}

您的代码将变为:

class CompleteProfile extends Component {
  state = {
    completeProfile: false,
  }

  componentDidMount(){
    let { dispatch, session } = this.props
    dispatch(getMandatoryFields(session.username))
  }

  componentDidUpdate() {
    console.log(
      'this.props.mandatory_fields.updateNeeded -- ' +
        this.props.mandatory_fields.updateNeeded
    )
    if (this.props.mandatory_fields.updateNeeded !== false) {
      this.setState({
        completeProfile: this.props.mandatory_fields.updateNeeded,
      })
    }
  }
...
...
....
const mapStateToProps = state => ({
  mandatory_fields: state.User.mandatory_fields,
  session: state.User.session,
})

export default connect(mapStateToProps)(CompleteProfile)

推荐阅读