React - ComponentDidMount 没有从 Redux 状态中获取value

IT技术 reactjs redux
2021-05-23 04:28:38

我正在正确更新 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 状态图像所示。我错过了什么?

2个回答

你必须检查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)

使用@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,
    })
  }
}