本文介绍了使用 redux-form 异步加载数据不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 redux-form v6.7.0 异步加载数据以形成表单,但它不起作用.我提到了这个链接.下面是我的示例代码.任何帮助,将不胜感激.提前致谢.
I am trying to load data to form asynchronously using redux-form v6.7.0, but it is not working. I referred this link. Below is my sample code. Any help would be appreciated. Thanks in advance.
/* 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 = ReduxbineReducers({ personInfo: PersonInfoReducer, form: ReduxForm.reducer }); const store = Redux.createStore(allReducers); ReactDOM.render(<ReactRedux.Provider store={store}><FormSample /></ReactRedux.Provider>, document.getElementById("root")); <script src="cdnjs.cloudflare/ajax/libs/react/15.1.0/react.min.js"></script> <script src="cdnjs.cloudflare/ajax/libs/react/15.1.0/react-dom.min.js"></script> <script src="cdnjs.cloudflare/ajax/libs/redux/3.7.2/redux.min.js"></script> <script src="cdnjs.cloudflare/ajax/libs/react-redux/5.0.6/react-redux.min.js"></script> <script src="cdnjs.cloudflare/ajax/libs/redux-form/6.7.0/redux-form.min.js"></script> <div id="root"></div> 推荐答案在调用 Redux Form 高阶组件时需要将 enableReinitialize 设置为 true ,以便其更新从 Redux 状态接收新 props 时的初始值:
You need to set enableReinitialize to true when calling Redux Form higher order component, so that it updates the initial values when it receives new props from the Redux state:
FormSample = ReduxForm.reduxForm({ form: 'FormSample', enableReinitialize: true })(FormSample);参见 redux-form/6.0.2/examples/initializeFromState/
更多推荐
使用 redux
发布评论