I am getting the Redux state updated correctly. Here is what the Redux state of updateNeeded
is (In this case it is true).
我正在控制台记录该值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 状态图所示。我缺少什么?
你必须检查this.props.mandatory_fields.updateNeeded
in componentDidUpdate
钩。更改 Redux 状态后,组件将被更新。所以你必须检查props
in 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)