如何遍历包含嵌套数组的响应对象中的tours属性?
Alright, let's figure out why your map() method isn't working with the tours data. The issue boils down to how you're handling the API response in your Redux thunk:
The Root Cause
Your API returns a structured response object that looks like this:
{ status: 'Success', length: 7, data: { tours: [/* 7 tour objects */] } }
Right now, you're dispatching the entire top-level response object to your getTours action with dispatch(getTours(data));. Since your initial tours state is an empty array, you're replacing that array with the full response object—so when you try to run map() on it later, you're calling an array method on a plain object, which will throw an error or do nothing. Using Object.entries() here also doesn't help because you don't need to convert an object to an array; you just need to grab the actual tours array nested inside the response.
The Simple Fix
Update your getData thunk to pass only the tours array to the getTours action. You need to drill into the nested data.tours property of the API response:
export const getData = () => { return async (dispatch) => { try { dispatch(isLoading(true)); const res = await fetch(`http://localhost:5555/api/bc1/tours`); if (!res.ok) { throw new Error(`Error while connecting with server`); } // Rename variable to avoid confusion with the nested "data" property const apiResponse = await res.json(); dispatch(isLoading(false)); // Pass the actual tours array to your action dispatch(getTours(apiResponse.data.tours)); } catch (error) { dispatch( checkStatus({ title: `Error`, message: error.message, }) ); } }; };
How to Verify
If you want to confirm the response structure before using it, add a quick console.log right after parsing the JSON:
const apiResponse = await res.json(); console.log('Full API Response:', apiResponse); console.log('Extracted Tours Array:', apiResponse.data.tours);
This will show you exactly what data you're working with and ensure you're targeting the correct array.
Once you dispatch the actual tours array to your Redux state, you'll be able to use map() on it as expected—since your state will now hold an array instead of a top-level response object.
内容的提问来源于stack exchange,提问作者aisha sharma

