reactjs - 在 Redux-Form 中编辑和提交后如何更新我的 initialValues?
问题描述
我目前有一个 Redux 形式的表单,它从 API 中提取初始值。但是,每当我编辑其中一个值然后提交表单时,它都会返回旧的初始值(似乎没有更新)。我希望能够编辑该字段,提交,然后将初始值更新为新值,以便在再次加载表单时,您将看到最近的编辑/更改。现在,这就是我初始化数据的方式:
componentDidMount(){
this.props.offerCallBack()
.then(c => {
this.setState({
offerContent: c,
});
this.handleInitialize();
})
.catch(error => {
console.log(error);
});
}
handleInitialize() {
const offerContent = JSON.parse(this.state.offerContent.content);
const initData = {
"questionText": offerContent.question_text === null ? "Enter Question Text" : offerContent.question_text,
"questionType": offerContent.question_type === null ? "" : offerContent.question_type,
this.props.initialize(initData);
}
这是我的提交功能:
onSubmit(values) {
console.log(values);
const questionData = Object.assign({}, values, { questionText: undefined });
this.props.saveOffer(questionData);
}
我的其中一个字段的示例
<Field
name="questionText"
type="text"
id="questionText"
component={renderField}
label="Question Text"
onChange={this.handleChange}
/>
然后是我的 redux 表单的底部
const form = reduxForm({
form: 'offerquestion',
enableReinitialize: true
});
function mapStateToProps(state) {
return {
offerContent: state.offerContent,
initialValues: state.offerContent
};
}
export default connect(mapStateToProps)(form(OfferExample));
任何和所有的帮助将不胜感激,我已经坚持了好几天了!
解决方案
看起来您正在使用state
inhandleInitilize
方法,请记住,当您setState
状态不正确更新时(它是一个异步函数)。因此,如果您向 setState 添加回调,然后调用该handleInitialize
方法,您就可以确定该值存在。
componentDidMount(){
this.props.offerCallBack()
.then(c => {
this.setState({
offerContent: c,
}, () => {
// You can handle here and make sure the state has updated
console.log( this.state.offerContent );
this.handleInitialize();
});
})
.catch(error => {
console.log(error);
});
}
推荐阅读
- python - 不同功能的结果以制作收据
- javascript - Sequelize hasOne() / hasMany() 和 BelongsTo() 复制外键(创建一个新的并重新定义它),并重新宣布它为键
- amazon-web-services - 为什么 AWS 将停用具有多容器支持的 Elastic Beanstalk?
- javascript - 是否可以访问这些符号中的任何一个?
- python-3.x - TypeError:输入类型不支持 ufunc 'bitwise_and'
- android - 如何在 Jetpack Compose 中从项目屏幕正确分发 @Previews
- magento - 如何在管理端插件的自定义模块中添加重置密码功能?
- algorithm - 如果你有一个 O(n^3) 的算法,那么你可以用一台速度快 10 倍的计算机同时处理多少个元素?
- c - 声明计数器时比较 uint8_t 与 uint16_t
- c - 创建一个使用 srand 和 rand 生成随机数的函数