首页 > 解决方案 > 在 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));

任何和所有的帮助将不胜感激,我已经坚持了好几天了!

标签: reactjsreduxredux-form

解决方案


看起来您正在使用stateinhandleInitilize方法,请记住,当您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);
     });
 }

推荐阅读