mapStateToProps被调用两次,redux-form表单值获取报错求助
Fixing "Cannot read property 'values' of undefined" in redux-form's SurveyFormReview
Hey there! Let's break down what's going on with your redux-form issue and get it sorted out.
First, let's tackle the error: "cannot read property 'values' of undefined"
This error pops up because when your component tries to access values, the parent form state object from Redux is undefined. Here are the most common fixes:
- Double-check your state path in mapStateToProps
Redux-form stores all form state under theformkey in your Redux store by default. If your form has anameprop set to something likesurveyForm, your mapStateToProps should include safety checks to avoid undefined errors:
const mapStateToProps = (state) => { // Use optional chaining or fallback values to safely access form data return { formValues: state.form?.surveyForm?.values || {} }; };
If you were trying to access state.surveyForm.values directly (skipping the form key), that's the root issue—redux-form doesn't store form state at the root of your store unless you explicitly configured it to.
- Handle the initial mount state
When your SurveyFormReview component first loads, the form might not have any saved values yet, sostate.form.surveyFormcould be undefined. Adding a fallback empty object ensures you never try to accessvalueson a non-existent object. You can also add a quick check in your component before rendering:
const SurveyFormReview = ({ formValues }) => { // Show a loading state if no form values are ready yet if (!Object.keys(formValues).length) { return <div>Preparing your preview...</div>; } // Render your preview content here return ( <div> <h3>Your Form Preview</h3> <p>Name: {formValues.name}</p> {/* Render other form fields */} </div> ); };
- Verify your Redux store configuration
Make sure you've properly merged the redux-form reducer into your root reducer. If you skipped this step,state.formwon't exist at all:
import { combineReducers } from 'redux'; import { reducer as formReducer } from 'redux-form'; const rootReducer = combineReducers({ // Your other app reducers go here form: formReducer // This line is mandatory for redux-form to work! });
Why is mapStateToProps being called twice?
Don't stress—this is totally normal behavior!
- The first call happens when your component initializes and connects to the Redux store.
- The second call triggers when the form state updates (either when you navigate to the preview, or when form values change).
As long as you've added the safety checks we talked about, this double call won't cause any problems.
Give these steps a try, and your preview component should start working as expected!
内容的提问来源于stack exchange,提问作者Harrison Crews
相关产品推荐
相关产品推荐

