【问题标题】:How can I update my initialValues after they are edited and submitted in Redux-Form?在 Redux-Form 中编辑和提交后如何更新我的 initialValues?
【发布时间】:2019-03-12 18:44:36
【问题描述】:

我目前有一个 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));

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

【问题讨论】:

    标签: reactjs redux redux-form


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 2017-08-26
      • 2017-12-18
      相关资源
      最近更新 更多