reactjs - React - ComponentDidMount 没有从 Redux 状态中获取价值
问题描述
我正在正确更新 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 状态图所示。我错过了什么?
解决方案
您必须签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)
推荐阅读
- python - 遍历列并划分列值并在列中创建新列
- php - 如何从 Laravel Debug 中删除环境变量?
- c# - 我可以在 ASP.NET Core 中创建一个类似于 Laravel 资源控制器的控制器吗?
- reactjs - 动态设置 react-table 的 show 属性不显示或隐藏列,反之亦然
- html - HTML在VB6中的标签内选择文本
- android - 如何为空值设置 JSONObject 默认字符串
- r2dbc - 如何使用 Spring Data R2DBC 控制事务流的流程?
- javascript - SVG - 没有图像填充的圆形中心图像
- android - 使用数据绑定更新对象类型 LiveData
- javascript - 替换字符串中的浮点数