ReactJS中如何将fetch的返回结果保存到变量中?
Let's walk through how to implement that onClick function to update your urlImages array, including reusing the fetch result stored in obj for the second request.
Step 1: Set Up State in Your React Component
First, make sure you're using React's useState hook to manage the urlImages array—this will let you update and render the new image URLs when a user clicks:
import { useState } from 'react'; function CollectionGallery() { const [urlImages, setUrlImages] = useState([]); // ... rest of your component code }
Step 2: Create the onClick Handler Function
We'll write an async function that first fetches the collection data (storing it in obj), then uses that data to fetch the corresponding image URLs, and finally updates the state.
Assuming each collection item has a unique id you can pass to the handler:
const handleCollectionImageClick = async (collectionId) => { try { // First fetch: Get collection data and store it in `obj` const collectionRes = await fetch(`/api/collections/${collectionId}`); const obj = await collectionRes.json(); // Second fetch: Use `obj` (e.g., its id) to get associated image URLs const imagesRes = await fetch(`/api/collections/${obj.id}/images`); const fetchedImages = await imagesRes.json(); // Update the urlImages state with the new array setUrlImages(fetchedImages); } catch (err) { console.error('Failed to fetch collection or images:', err); // You can add user-facing error feedback here too, like a toast message } };
Step 3: Attach the Handler to Your Images
When rendering your collection images, bind the onClick event to the handler, passing the collection's unique ID so we know which images to fetch:
// Example: Rendering your collection items return ( <div className="collection-grid"> {yourCollectionData.map(collection => ( <div key={collection.id} className="collection-item"> <img src={collection.thumbnail} alt={`${collection.name} thumbnail`} onClick={() => handleCollectionImageClick(collection.id)} /> <p>{collection.name}</p> </div> ))} {/* Display the updated urlImages array */} <div className="selected-images"> {urlImages.map((imgUrl, index) => ( <img key={index} src={imgUrl} alt="Collection detail" /> ))} </div> </div> );
Key Notes to Keep in Mind
- Backend API Requirements: Make sure your Node backend has two endpoints set up:
GET /api/collections/:id: Returns the full collection object with necessary data (like itsidto link to images)GET /api/collections/:collectionId/images: Returns an array of image URLs associated with that collection
- Error Handling: The try/catch block prevents unhandled promise rejections if a fetch fails—you can expand this to show user-friendly errors (e.g., a banner saying "Oops, couldn't load those images").
- Caching (Optional): If users might click the same collection multiple times, consider adding a cache (like a
useRefobject) to store already fetchedobjdata, so you don't make duplicate unnecessary requests.
内容的提问来源于stack exchange,提问作者Mich

