问题
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 = 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:
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);
See http://redux-form.com/6.0.2/examples/initializeFromState/
来源:https://stackoverflow.com/questions/45763383/load-data-asynchronously-not-working-using-redux-form