在AJAX调用之后更新Redux InitialValues

时间:2017-07-26 14:17:47

标签: javascript reactjs redux redux-form

我正在构建一个表单,在某些情况下,表单元素是从AJAX调用注入的(例如,重复文本输入)。

一切都运行良好并更新我的表单但是我似乎无法将任何默认值恢复到我的redux商店中的初始表单状态。下面是我自定义的reducer,它跟踪表单元素。我可以再次将新值推入初始状态吗?

//Schema Reducer
case "UPDATE_SCHEMA_FULFILLED":{

        let s = {...state.schema}
        for (let key in action.payload){
            if(s.hasOwnProperty(key)){
                if(key == 'values'){
                    s[key] = {...s[key], ...action.payload[key]}
                }else{
                    s[key] = [...s[key], ...action.payload[key]]
                }

            }
        }

        state = { ...state, 
            loaded: true,
            schema: {...s},
        }
        break;
    }

我的表单是根据文档在第一次加载时添加初始值:

CustomForm = connect(
  state => ({
initialValues: state.schema.schema.values
  }),
  dispatch => ({
    onSubmit: data => dispatch(saveForm(data))
  })
)(CustomForm)

这就是生成动作的原因:

import React from 'react'
import { addSchema } from '../actions/schemaActions'

export default class VirtualButton extends React.Component {
constructor(){
    super();
    this.generateNewLayout = this.generateNewLayout.bind(this)
}

generateNewLayout(e){
    e.preventDefault();
    this.props.dispatch(addSchema(this.props.owner));
}

render(){

    return <div className="cf__virtual-action"><a href="" onClick={this.generateNewLayout}>Create New</a></div>

}
}

1 个答案:

答案 0 :(得分:0)

这似乎有效,但我不确定它是否具有高效性?通过props将初始化值函数添加到操作中:

//My button that dispatches the initial call:
this.props.dispatch(addSchema(this.props.owner, this.props.initialize, this.props.initialValues));

export function addSchema($id, initialize, initial){
return function(dispatch) {
    axios.post(config.api+'forms/schema/virtual/'+$id)
    .then((response) => {
        dispatch({type: 'UPDATE_SCHEMA_FULFILLED', payload: response.data})
        initialize({...initial, ...response.data.values});
    })
    .catch((error) => {
        console.log(error);
    })
}
}