You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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:

  1. API Function Context
    Your API layer wraps the axios response into an object with a data key:

    // 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)}
    };
    
  2. createAsyncThunk Setup
    The value returned by your API function becomes action.payload in 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
      }
    );
    
  3. Retrieve the Array in Fulfilled Callback
    In the slice's extraReducers, use action.payload.data to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:40:43