在页面加载时以 redux 形式传递初始值
Passing initial values in redux form on page load
我正在将初始值传递给 redux 表单。我在 componentWillMount 时获取数据。
加载页面时,出现错误,无法读取未定义的 属性 'id'。如果我刷新页面,数据就会在那里。
谁能帮帮我。
这是我的代码。
componentWillMount() {
this.props.actions.getService(this.props.params.Id);
}
const mapStateToProps = (state) => {
return {
initialValues: {
user_id:state.userInfo.data.user.id,
}
}
}
谢谢。
另一种方法是使用 this.props.initialize,这是 Redux Form 为您添加的。您还可以使用 lodash 的 .get 方法来避免像这样添加大量检查:if (nextState.userInfo && nextState.userInfo.data && nextState.userInfo.data.user && nextState.userInfo。 data.user.id && nextState.userInfo.data.user.id !== this.state.userInfo.data.user.id)
像这样的东西应该可以工作:
componentWillReceiveProps = (nextProps) => {
if (_.get(nextProps, 'userInfo.data.user.id') !== _.get(this.props, 'userInfo.data.user.id')) {
this.props.initialize({ user_id: nextProps.userInfo.data.user.id });
}
}
mapStateToProps = (state) => {
return {
userInfo: state.userInfo,
};
}
我正在将初始值传递给 redux 表单。我在 componentWillMount 时获取数据。
加载页面时,出现错误,无法读取未定义的 属性 'id'。如果我刷新页面,数据就会在那里。
谁能帮帮我。
这是我的代码。
componentWillMount() {
this.props.actions.getService(this.props.params.Id);
}
const mapStateToProps = (state) => {
return {
initialValues: {
user_id:state.userInfo.data.user.id,
}
}
}
谢谢。
另一种方法是使用 this.props.initialize,这是 Redux Form 为您添加的。您还可以使用 lodash 的 .get 方法来避免像这样添加大量检查:if (nextState.userInfo && nextState.userInfo.data && nextState.userInfo.data.user && nextState.userInfo。 data.user.id && nextState.userInfo.data.user.id !== this.state.userInfo.data.user.id)
像这样的东西应该可以工作:
componentWillReceiveProps = (nextProps) => {
if (_.get(nextProps, 'userInfo.data.user.id') !== _.get(this.props, 'userInfo.data.user.id')) {
this.props.initialize({ user_id: nextProps.userInfo.data.user.id });
}
}
mapStateToProps = (state) => {
return {
userInfo: state.userInfo,
};
}