我正在更新Redux状态。以下是updateNeeded
的Redux状态(在这种情况下是真的)。
我是控制台记录值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
钩子里检查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)
使用@ 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,
})
}
}