在React Redux中处理数组:如何访问异步返回的嵌套数据?
Accessing Array Data in Redux Slice Fulfilled Callback
Since your async API function returns an object with a data property containing the target array, you can directly access the array via action.payload.data in the fulfilled callback of your Redux slice.
Step-by-Step Implementation:
API Function Context
Your API layer wraps the axios response into an object with adatakey:// api.js import axios from 'axios'; export const fetchTargetData = async () => { const response = await axios.get('/api/your-endpoint'); return { data: response.data }; // Returns {data: Array(17)} };createAsyncThunk Setup
The value returned by your API function becomesaction.payloadin the slice's callbacks:// dataSlice.js import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'; import { fetchTargetData } from './api'; export const fetchDataThunk = createAsyncThunk( 'data/fetch', async () => { const apiResult = await fetchTargetData(); return apiResult; // Passes {data: Array(17)} to action.payload } );Retrieve the Array in Fulfilled Callback
In the slice'sextraReducers, useaction.payload.datato access and store the array:const dataSlice = createSlice({ name: 'data', initialState: { items: [], loading: false, error: null }, extraReducers: (builder) => { builder .addCase(fetchDataThunk.fulfilled, (state, action) => { state.loading = false; // Assign the array to state state.items = action.payload.data; }) .addCase(fetchDataThunk.pending, (state) => { state.loading = true; }) .addCase(fetchDataThunk.rejected, (state, action) => { state.loading = false; state.error = action.error.message; }); } }); export default dataSlice.reducer;
Optional: Safeguard Against Undefined Data
If the API might return no data, use optional chaining to avoid runtime errors:
state.items = action.payload?.data || [];
内容的提问来源于stack exchange,提问作者Omri ben shushan
相关产品推荐
相关产品推荐

