React - ComponentDidMount没有从Redux状态获取值

问题描述 投票:1回答:2

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

我是控制台记录值this.props.mandatory_fields.updateNeeded但它始终是我设置的初始状态。它没有从Redux State获得更新。下面是我进行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状态图所示。我错过了什么?

reactjs redux
2个回答
2
投票

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

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
投票

使用@ 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,
    })
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.