React引入redux-form报错:Cannot read property 'any' of undefined
Hey there! Looks like the main issue here is a version mismatch between your very old redux-form@4.1.3 and the newer React/React-Redux versions you're using (React 16.3.2, React-Redux 5.0.7). Redux Form v4 was built for much older React versions, so it's not playing nice with your current stack. Let's fix this step by step:
Step 1: Upgrade Redux-Form to a Compatible Version
First, uninstall the outdated v4 and install a stable v7 release (which works perfectly with your React/React-Redux setup):
# Uninstall old version npm uninstall redux-form # Install compatible v7 version npm install redux-form@7.4.2
Step 2: Update Your Form Component Code
Redux Form v7 changed the API significantly—you no longer use the fields prop, and instead use the <Field> component to wrap your inputs. Here's the updated post_new.js:
import React, { Component } from 'react'; import { reduxForm, Field } from 'redux-form'; class PostsNew extends Component { // Handle form submission onSubmit = (formValues) => { console.log('Form submitted:', formValues); // Add your submission logic here (e.g., API call) } render() { // Destructure handleSubmit from props const { handleSubmit } = this.props; return ( <form onSubmit={handleSubmit(this.onSubmit)}> <h3>Create a new post</h3> <div className="form-group"> <label>Title</label> {/* Use Field component, map to an input */} <Field name="title" component="input" type="text" className="form-control" /> </div> <div className="form-group"> <label>Categories</label> <Field name="categories" component="input" type="text" className="form-control" /> </div> <div className="form-group"> <label>Content</label> {/* Map Field to textarea */} <Field name="content" component="textarea" className="form-control" /> </div> <button type="submit" className="btn btn-primary">Submit</button> </form> ); } } // Configure reduxForm - no more "fields" property needed export default reduxForm({ form: 'PostsNewForm' })(PostsNew);
Key Changes Explained:
- We import
Fieldfromredux-formto connect each input to the form state - The
fieldsarray in thereduxFormconfig is removed—v7 automatically tracks fields by theirnameprop handleSubmitis pulled from component props, and we pass our customonSubmithandler to it- Each input/textarea is replaced with a
<Field>component, which handles connecting to the Redux store automatically
Step 3: Verify Reducer Setup
Your reducer code in reducers/index.js is already correct for v7—no changes needed here! The formReducer import and combineReducers setup is still valid.
Once you've made these changes, restart your development server and the error should be gone. You'll now have a working form that connects to Redux correctly.
内容的提问来源于stack exchange,提问作者Tje123

