反应-ComponentDidMount没有从Redux状态获得价值

时间:2018-09-03 02:21:46

标签: reactjs redux

我正在正确更新Redux状态。这是updateNeeded的Redux状态(在这种情况下为true)。 enter image description here

我正在控制台记录值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状态图像所示。我想念什么?

2 个答案:

答案 0 :(得分:2)

您必须在this.props.mandatory_fields.updateNeeded钩中选中componentDidUpdate。更改Redux状态后,组件将更新。因此,您必须在props中检查componentDidUpdate,而不是在调用dispatch之后立即检查。您可以看到我的代码:

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)

答案 1 :(得分:1)

使用@Max的解决方案,您的整个新代码应如下所示:

componentDidUpdate(prevProps) {
  let { dispatch, session } = this.props
  dispatch(getMandatoryFields(session.username))
  console.log(
    'this.props.mandatory_fields.updateNeeded -- ' +
      this.props.mandatory_fields.updateNeeded
  );
  if (!prevProps.mandatory_fields.updateNeeded && this.props.mandatory_fields.updateNeeded) {
    this.setState({
      completeProfile: this.props.mandatory_fields.updateNeeded,
    })
  }
}