使用redux-forms能否在两个表单视图间共享状态?及替代方案咨询
Absolutely, sharing the same Redux store between your View1 and View2 is not only possible but the standard approach for this kind of cross-view data sync scenario with Redux (and redux-forms specifically). Let’s walk through how to implement this cleanly, plus cover alternative options if you want to explore other paths.
This is the most straightforward way to keep your student data in sync across views, since Redux’s entire purpose is to provide a single source of truth for your app’s state.
1. Normalize Your Student Data Model
First, structure your student data in the store so it’s easy for both views to access and modify. A normalized model might look like this:
{ student: { id: "unique-student-id", firstName: "Chirag", lastName: "Paryani", course: "Full Stack Development", contactDetails: [ { type: "email", value: "chirag@example.com" }, { type: "phone", value: "555-9876" } ] } }
This way, View1 handles the top-level fields (firstName, lastName, course), and View2 manages the contactDetails array—both operating on the same student object in the store.
2. Sync redux-forms with Your Shared Store
redux-forms integrates seamlessly with Redux, so you have two solid options here:
Option 1: Use the same form name for both views
Assign the sameformprop to both your View1 and View2 form components (e.g.,form="studentForm"). redux-forms will store all form fields under this single key in the Redux store. For View2’s multi-group contact info, use redux-forms’FieldArraycomponent to manage the dynamic array of email/phone fields—it’s designed exactly for this use case.Option 2: Map form changes to your custom Redux slice
If you prefer to maintain control over your student state outside redux-forms’ built-in structure, dispatch custom actions when form fields change. For example, in View1’sFirstNamefield, useredux-form’schangeaction or a custom action to update yourstudentslice directly:import { useDispatch } from 'react-redux'; import { change } from 'redux-form'; function View1FirstNameField() { const dispatch = useDispatch(); const handleChange = (e) => { // Update redux-form's state dispatch(change('studentForm', 'firstName', e.target.value)); // Also update your custom student slice for cross-view access dispatch(updateStudentFirstName(e.target.value)); }; return <Field name="firstName" component="input" onChange={handleChange} />; }
3. Connect Both Views to the Shared State
Use React-Redux’s useSelector hook (or connect HOC for class components) to pull the latest student data into both views. For example, in View2:
import { useSelector } from 'react-redux'; function View2() { const studentFirstName = useSelector(state => state.student.firstName); const contactDetails = useSelector(state => state.student.contactDetails); // Now you can display the updated firstName from View1 here return ( <div> <p>Current Student: {studentFirstName}</p> {/* Use FieldArray to render/edit contactDetails */} </div> ); }
Any changes to firstName in View1 will immediately reflect in View2, since both are reading from the same store.
If you don’t want to rely fully on Redux for this scenario (e.g., for a simpler app), you can use:
- Parent component local state + Context API: Store the full student data in a parent component’s state, then pass the data and update functions down to View1 and View2 via props or React Context. Here’s a quick example:
import { useState } from 'react'; import { Switch, Route } from 'react-router-dom'; function StudentManager() { const [studentData, setStudentData] = useState(initialStudentData); const updateStudent = (updates) => { setStudentData(prev => ({ ...prev, ...updates })); }; return ( <Switch> <Route path="/view1"> <View1 student={studentData} onUpdate={updateStudent} /> </Route> <Route path="/view2"> <View2 student={studentData} onUpdate={updateStudent} /> </Route> </Switch> ); } - When you’re ready to save to the database, just send the complete
studentDataobject from the parent (or either view) to your backend API.
- For View2’s multi-group contact fields,
FieldArrayis your best friend—it handles adding/removing rows and syncing with the store automatically. - Regardless of the approach you choose, always send the full, merged student data (basic fields + contact info) to your database in a single update request to ensure consistency.
内容的提问来源于stack exchange,提问作者Chirag Paryani

