React JS:点击返回按钮时如何传递参数?
Hey there! Let's figure out how to pass values when clicking the back button in your React app. Based on your workflow (Landing → InstagramScraper → EditPhoto), here are several practical solutions tailored to different scenarios:
1. Pass Values via React Router Navigation State (Most Direct)
If you're using React Router (the standard for React navigation), you can attach state directly to the navigation action. This keeps your data encapsulated without cluttering the URL.
Step 1: Pass state when navigating to /editPhoto
In your InstagramScraper component:
import { useNavigate } from 'react-router-dom'; function InstagramScraper() { const navigate = useNavigate(); const brandName = // Your existing logic to get the selected brand name const handleImageClick = (imageData) => { // Attach brandName and image data to navigation state navigate('/editPhoto', { state: { brandName: brandName, originalImage: imageData } }); }; // Rest of your component code... }
Step 2: Retrieve state and handle back navigation in /editPhoto
In your EditPhoto component:
import { useNavigate, useLocation } from 'react-router-dom'; function EditPhoto() { const navigate = useNavigate(); const location = useLocation(); const { brandName, originalImage } = location.state || {}; const handleGoBack = (editedImage) => { // Pass edited image data back to InstagramScraper if needed navigate(-1, { state: { editedImage: editedImage, brandName: brandName } }); }; return ( <div> {/* Your image editing UI */} <button onClick={() => handleGoBack(yourEditedImageData)}>返回</button> </div> ); }
Step 3: Read returned state in InstagramScraper
Add this to your InstagramScraper component to capture the edited data when returning:
import { useLocation, useEffect } from 'react-router-dom'; import { useState } from 'react'; function InstagramScraper() { const location = useLocation(); const [updatedImage, setUpdatedImage] = useState(null); useEffect(() => { // Check for returned state when navigating back if (location.state?.editedImage) { setUpdatedImage(location.state.editedImage); // Update your image list or perform other actions here } }, [location]); // Rest of your component code... }
2. Use URL Parameters (For Simple, Shareable Values)
If your brand name is a short, serializable string, you can append it to the URL. This makes the state visible and shareable, though it's not ideal for sensitive or large data.
Navigate with URL params from InstagramScraper:
const handleImageClick = (imageData) => { const encodedBrand = encodeURIComponent(brandName); navigate(`/editPhoto?brand=${encodedBrand}&imageId=${imageData.id}`); };
Retrieve params in EditPhoto:
import { useSearchParams, useNavigate } from 'react-router-dom'; function EditPhoto() { const [searchParams] = useSearchParams(); const navigate = useNavigate(); const brandName = decodeURIComponent(searchParams.get('brand')); const imageId = searchParams.get('imageId'); const handleGoBack = () => { // No need to pass brand name back—it's already in the app state or URL navigate(-1); }; // Rest of your component code... }
3. Global State Management (For Complex Apps)
If you have multiple components sharing state (like the selected brand or edited images), use React's Context API or Redux to keep data accessible across your app.
Example with Context API:
First create a context provider:
import { createContext, useContext, useState } from 'react'; const AppContext = createContext(); export function AppProvider({ children }) { const [currentBrand, setCurrentBrand] = useState(''); const [editedImage, setEditedImage] = useState(null); return ( <AppContext.Provider value={{ currentBrand, setCurrentBrand, editedImage, setEditedImage }}> {children} </AppContext.Provider> ); } export function useAppContext() { return useContext(AppContext); }
Update state in Landing when selecting a brand:
function Landing() { const { setCurrentBrand } = useAppContext(); const navigate = useNavigate(); const handleBrandSelect = (brand) => { setCurrentBrand(brand); navigate('/instagramScraper'); }; // Rest of your component code... }
Use state in EditPhoto and update on return:
function EditPhoto() { const { setEditedImage } = useAppContext(); const navigate = useNavigate(); const handleSaveAndGoBack = (editedImg) => { setEditedImage(editedImg); navigate(-1); }; // Rest of your component code... }
Read updated state in InstagramScraper:
function InstagramScraper() { const { currentBrand, editedImage } = useAppContext(); useEffect(() => { if (editedImage) { // Update your image list or process the edited image here // Optional: Clear the edited image state after use // setEditedImage(null); } }, [editedImage]); // Rest of your component code... }
4. LocalStorage/SessionStorage (For Persistent Data)
If you need data to survive page refreshes, use browser storage. Just note this is best for non-sensitive data.
Save data before navigating to EditPhoto:
const handleImageClick = (imageData) => { localStorage.setItem('currentBrand', brandName); localStorage.setItem('currentImage', JSON.stringify(imageData)); navigate('/editPhoto'); };
Retrieve data and save edits in EditPhoto:
const handleGoBack = (editedImage) => { localStorage.setItem('editedImage', JSON.stringify(editedImage)); navigate(-1); };
Read saved data in InstagramScraper:
useEffect(() => { const editedImg = localStorage.getItem('editedImage'); if (editedImg) { setUpdatedImage(JSON.parse(editedImg)); localStorage.removeItem('editedImage'); // Clean up after use } }, []);
内容的提问来源于stack exchange,提问作者Shabina Rayan

