You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Redux Form值更新Redux Store?React新手遇状态传递异常

Hey there! Let's work through your Redux Form issue step by step—since you're new to React and Redux Form, I'll keep this straightforward and actionable.

First, Let's Diagnose the Core Issues

From what you described, the main problems are likely:

  1. Missing Redux Form's required reducer in your store setup
  2. Incorrectly connecting your components to the Redux store (especially the "INFORMATION COMPONENT" and your form)
  3. No default initial state, leading to undefined when passing props

Step 1: Fix Your Redux Store Configuration

Redux Form relies on its own reducer to manage form state. If you haven't added it to your root reducer, your form won't sync with the store at all.

import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
// Import your custom reducers here (like the one for your INFORMATION state)
import infoReducer from './infoReducer';

const rootReducer = combineReducers({
  form: formReducer, // THIS IS REQUIRED—Redux Form needs this to work
  informationState: infoReducer // Your custom state slice
});

export default rootReducer;

Step 2: Properly Build Your Form Component with Redux Form

Your form component needs two layers of wrapping: first with reduxForm() (to handle form logic), then with connect() (to link to your custom store state/actions).

import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';

class YourForm extends Component {
  // Render a reusable input field
  renderInput = ({ input, label, meta: { touched, error } }) => (
    <div>
      <label>{label}</label>
      <input {...input} type="text" />
      {touched && error && <span className="error">{error}</span>}
    </div>
  );

  // Handle form submission (dispatch action to update your custom state)
  handleSubmit = (formValues) => {
    this.props.updateInformationState(formValues);
  };

  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={handleSubmit(this.handleSubmit)}>
        <Field name="name" component={this.renderInput} label="Name" />
        <Field name="email" component={this.renderInput} label="Email" />
        <button type="submit">Save</button>
      </form>
    );
  }
}

// Optional: Add form validation
const validate = (values) => {
  const errors = {};
  if (!values.name) errors.name = 'Name is required';
  if (!values.email) errors.email = 'Email is required';
  return errors;
};

// Wrap the form with reduxForm first
const ReduxWrappedForm = reduxForm({
  form: 'informationForm', // Unique identifier for this form
  validate // Optional validation
})(YourForm);

// Connect to your custom store state and actions
const mapStateToProps = (state) => ({
  // Pre-populate form with existing state (avoids undefined)
  initialValues: state.informationState
});

const mapDispatchToProps = (dispatch) => ({
  updateInformationState: (values) => dispatch({
    type: 'UPDATE_INFORMATION',
    payload: values
  })
});

// Final export: connect + reduxForm wrapped component
export default connect(mapStateToProps, mapDispatchToProps)(ReduxWrappedForm);

Step 3: Fix Your "INFORMATION COMPONENT"

If your INFORMATION COMPONENT is supposed to pass state to the form, it needs to be a React component connected to the store (non-React classes can't pass props to React components directly). Here's how to set it up:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import YourForm from './YourForm';

class InformationComponent extends Component {
  render() {
    // Debug: Check if state is loaded correctly (fix undefined here)
    console.log('Information State:', this.props.information);

    return (
      <div className="information-container">
        <h2>Your Information</h2>
        {/* Pass state to form via initialValues (already handled in form's mapStateToProps, but you can pass directly if needed) */}
        <YourForm />
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  information: state.informationState // Pull state from the store
});

export default connect(mapStateToProps)(InformationComponent);

Step 4: Ensure Your Custom Reducer Has Default Initial State

This is the most common cause of undefined state. Your reducer needs a default initial state so there's always something to pass:

// infoReducer.js
const initialState = {
  name: '',
  email: '' // Default empty values to avoid undefined
};

const infoReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'UPDATE_INFORMATION':
      return { ...state, ...action.payload };
    default:
      return state;
  }
};

export default infoReducer;

Quick Troubleshooting Tips

  • Use Redux DevTools to inspect your store—check if the form slice and your informationState slice exist and have values.
  • Double-check spelling in mapStateToProps (typos are a common culprit for undefined state).
  • Make sure your store is provided to all components via <Provider store={store}> in your root App component.

内容的提问来源于stack exchange,提问作者hangMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:15:01