使用redux-form异步加载数据不起作用

时间:2017-08-18 18:56:48

标签: javascript reactjs redux react-redux redux-form

我正在尝试使用redux-form v6.7.0异步加载数据,但它无法正常工作。我提到了link。以下是我的示例代码。任何帮助,将不胜感激。提前谢谢。

/* reducers should always maintain immutability */

var personInfo = {
  name: "",
  age: ""
};

function PersonInfoReducer(state = personInfo, action) {
  switch (action.type) {
    case "SAVE_PERSON_DATA":
      return Object.assign({}, state, action.payload);
default:
      return state;
  }
}

/* save person data action */
var savePersonData = (data) => {
  return {
    type: "SAVE_PERSON_DATA",
    payload: data
  };
};

/* form sample component */
class FormSample extends React.Component {
  componentDidMount() {
    const { initialize, savePersonData } = this.props;

    setTimeout(() => {
      var personInfo = {
        name: "Abraham",
        age: 21
      };
      savePersonData(personInfo);
    }, 3000);

  }

  componentWillReceiveProps(nextProps) {
    //console.log(nextProps);
    //debugger;
    //this.props.change("personName", nextProps.personInfo.name);
    //this.props.change("personAge", nextProps.personInfo.age);
  }

  render() {
    return (
      <form>
        <ReduxForm.Field name={"personName"} component="input" type="text" />
        <ReduxForm.Field name={"personAge"} component="input" type="text" />
        <h4>Values: </h4>{JSON.stringify(this.props.personInfo)}
      </form>
    );
  }
}

FormSample = ReduxForm.reduxForm({
    form: 'FormSample', // a unique identifier for this form
})(FormSample);

function mapStateToProps(state) {
  const { personInfo } = state;

  return {
    initialValues: personInfo,
    personInfo: personInfo
  };
}

function mapDispatchToProps(dispatch) {
  return Redux.bindActionCreators({
    savePersonData
  }, dispatch);
}

FormSample = ReactRedux.connect(mapStateToProps, mapDispatchToProps)(FormSample);


const allReducers = Redux.combineReducers({
  personInfo: PersonInfoReducer,
  form: ReduxForm.reducer
});

const store = Redux.createStore(allReducers);

ReactDOM.render(<ReactRedux.Provider store={store}><FormSample /></ReactRedux.Provider>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.7.2/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/5.0.6/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-form/6.7.0/redux-form.min.js"></script>

<div id="root"></div>

1 个答案:

答案 0 :(得分:1)

调用Redux Form高阶组件时,需要将enableReinitialize设置为true,以便在从Redux状态接收新道具时更新初始值:

FormSample = ReduxForm.reduxForm({
  form: 'FormSample',
  enableReinitialize: true
})(FormSample);

请参阅http://redux-form.com/6.0.2/examples/initializeFromState/