编辑:ReduxForm文档的更新解决方案
现在,最新版本的ReduxForm中记录了这一点,并且比我以前的答案简单得多.
在connect
使用ReduxForm进行装饰后,关键是表单组件.然后,您将能够initialValues
像组件上的任何其他道具一样访问道具.
// Decorate with reduxForm(). It will read the initialValues prop provided by connect() InitializeFromStateForm = reduxForm({ form: 'initializeFromState' })(InitializeFromStateForm) // now set initialValues using data from your store state InitializeFromStateForm = connect( state => ({ initialValues: state.account.data }) )(InitializeFromStateForm)
我通过使用redux-form reducer插件方法完成了这个.
以下演示获取异步数据并使用响应预先填充用户表单.
const RECEIVE_USER = 'RECEIVE_USER'; // once you've received data from api dispatch action const receiveUser = (user) => { return { type: RECEIVE_USER, payload: { user } } } // here is your async request to retrieve user data const fetchUser = (id) => dispatch => { return fetch('http://getuser.api') .then(response => response.json()) .then(json => receiveUser(json)); }
然后在包含redux-form
reducer的root reducer中包含reducer插件,该插件使用返回的读取数据覆盖表单值.
const formPluginReducer = { form: formReducer.plugin({ // this would be the name of the form you're trying to populate user: (state, action) => { switch (action.type) { case RECEIVE_USER: return { ...state, values: { ...state.values, ...action.payload.user } } default: return state; } } }) }; const rootReducer = combineReducers({ ...formPluginReducer, ...yourOtherReducers });
最后,您可以将新的formReducer与应用中的其他Reducer结合使用.
注意以下假定获取的用户对象的键与用户表单中的字段名称匹配.如果不是这种情况,则需要对要映射字段的数据执行其他步骤.