React中如何在两个页面间传递输入数据?
Hey there! Let's break down how to get your user input from one page to another in React—sounds like you're close, just need to tweak a few things. Here are some straightforward, actionable solutions tailored to your goal of showing a list of submitted entries on the second page:
1. React Router with State (Quick & Simple for Basic Navigation)
If you're using React Router (the most common way to handle page routing in React), you can pass input data directly via route state when navigating. This works great for temporary data that doesn't need to persist across page refreshes.
Input Page (e.g., InputPage.js)
import { useNavigate } from 'react-router-dom'; import { useState } from 'react'; function InputPage() { const [inputValue, setInputValue] = useState(''); const navigate = useNavigate(); const handleSubmit = (e) => { e.preventDefault(); if (inputValue.trim()) { // Pass the input value as state when navigating to entries page navigate('/entries', { state: { newEntry: inputValue } }); setInputValue(''); } }; return ( <form onSubmit={handleSubmit}> <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="Enter your entry" /> <button type="submit">Submit</button> </form> ); } export default InputPage;
Entries Page (e.g., EntriesPage.js)
import { useLocation } from 'react-router-dom'; import { useState, useEffect } from 'react'; function EntriesPage() { const [entries, setEntries] = useState([]); const location = useLocation(); useEffect(() => { // Check for the passed state and add to entries list if (location.state?.newEntry) { setEntries(prevEntries => [...prevEntries, location.state.newEntry]); // Clear the state to avoid duplicate entries if user navigates back/forth location.state = null; } }, [location.state]); return ( <div> <h2>Your Submitted Entries</h2> <ul> {entries.map((entry, index) => ( <li key={index}>{entry}</li> ))} </ul> </div> ); } export default EntriesPage;
2. LocalStorage/SessionStorage (Persistent Data)
If you need entries to stay even after a page refresh, use browser storage. This is perfect for simple data persistence without needing a backend or complex state management.
Updated Input Page Submit Handler
const handleSubmit = (e) => { e.preventDefault(); if (inputValue.trim()) { // Get existing entries from localStorage (or empty array if none) const existingEntries = JSON.parse(localStorage.getItem('entries')) || []; // Add new entry to the list const updatedEntries = [...existingEntries, inputValue]; // Save back to localStorage localStorage.setItem('entries', JSON.stringify(updatedEntries)); // Navigate to entries page navigate('/entries'); setInputValue(''); } };
Updated Entries Page
import { useState, useEffect } from 'react'; function EntriesPage() { const [entries, setEntries] = useState([]); useEffect(() => { // Load entries from localStorage when component mounts const storedEntries = JSON.parse(localStorage.getItem('entries')) || []; setEntries(storedEntries); }, []); return ( <div> <h2>Your Saved Entries</h2> <ul> {entries.map((entry, index) => ( <li key={index}>{entry}</li> ))} </ul> </div> ); }
3. Context API (Lightweight Cross-Component State)
If you want to share the entries list across multiple components (not just these two pages), Context API is a simpler alternative to Redux. It lets you manage state globally without the overhead of Redux setup.
Step 1: Create an Entry Context (EntryContext.js)
import { createContext, useContext, useState } from 'react'; const EntryContext = createContext(); export function EntryProvider({ children }) { const [entries, setEntries] = useState([]); const addEntry = (entry) => { setEntries(prev => [...prev, entry]); }; return ( <EntryContext.Provider value={{ entries, addEntry }}> {children} </EntryContext.Provider> ); } export function useEntryContext() { return useContext(EntryContext); }
Step 2: Wrap Your App with the Provider (App.js)
import { EntryProvider } from './EntryContext'; import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import InputPage from './InputPage'; import EntriesPage from './EntriesPage'; function App() { return ( <EntryProvider> <Router> <Routes> <Route path="/" element={<InputPage />} /> <Route path="/entries" element={<EntriesPage />} /> </Routes> </Router> </EntryProvider> ); } export default App;
Step 3: Use Context in Input & Entries Pages
Input Page
import { useNavigate } from 'react-router-dom'; import { useState } from 'react'; import { useEntryContext } from './EntryContext'; function InputPage() { const [inputValue, setInputValue] = useState(''); const navigate = useNavigate(); const { addEntry } = useEntryContext(); const handleSubmit = (e) => { e.preventDefault(); if (inputValue.trim()) { addEntry(inputValue); navigate('/entries'); setInputValue(''); } }; // ... rest of the component remains the same }
Entries Page
import { useEntryContext } from './EntryContext'; function EntriesPage() { const { entries } = useEntryContext(); // ... rest of the component remains the same }
Quick Note on Your Previous Attempts
- Refs: These are meant for accessing DOM elements, not passing data between pages—so that's why that didn't work.
- Props: Props only work between parent/child components, not across routed pages (unless you're using nested routes, which isn't your case here).
- Redux: This would work, but it's overkill for a simple entries list. Context API is a lighter alternative if you need global state.
内容的提问来源于stack exchange,提问作者Cuzto

