从json服务器提取Redux异步数据时出现问题

jaxagkaj  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(141)

我有一个简单的react CRUD表应用程序,在其中我设置了redux来执行添加、删除和更新功能,现在我正尝试使用redux从json服务器中提取数据。下面是我的切片的外观:

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

export const loadCustomers = createAsyncThunk("customer/load", async () => {
  const response = await fetch("http://localhost:8000/customers");

  const customers = await response.json();

  return { customers };
});

export const customerSlice = createSlice({
  name: "customers",
  initialState: { value: customers },
  reducers: {
    addCustomer: (state, action) => {
      state.value.push(action.payload);
    },

    deleteCustomer: (state, action) => {
      state.value = state.value.filter(customer => customer.id !== action.payload.id);
    },
    updateCustomer: (state, action) => {
      state.value.map(customer => {
        if (customer.id === action.payload.id) {
          customer.full_name = action.payload.full_name;
          customer.address = action.payload.address;
          customer.phone_number = action.payload.phone_number;
          customer.email = action.payload.email;
          customer.website = action.payload.website;
        }
      });
    },
  },
});

export const { addCustomer, deleteCustomer, updateCustomer } = customerSlice.actions;
export default customerSlice.reducer;

目前我得到的'customers'是没有定义no-undef当我尝试使用它在初始状态.什么是正确的方式来获得数据从json服务器与redux

9w11ddsr

9w11ddsr1#

初始状态是从Web服务器加载数据之前的状态,所以我假设它应该是一个空Array或undefined

initialState: { value: [] },

您可能需要确保客户已加载并在加载时显示动画。因为Web服务器可能会在20秒后返回响应。
因此,您的初始状态可能会变成:

initialState: { value: [], loaded: false, fetching: false },

另一种方法是使用createAsyncThunk中建议的状态变量

const loadingStatus = {
 idle: 'idle',
 pending: 'pending',
 succeeded: 'succeeded',
 failed: 'failed'
}

//...

initialState: { value: [], loading: loadingStatus.idle },

因此,在您的示例中,结果将是:

const loadingStatus = {
 idle: 'idle',
 pending: 'pending',
 succeeded: 'succeeded',
 failed: 'failed'
}

export const loadCustomers = createAsyncThunk("customer/load", async () => {
  const response = await fetch("http://localhost:8000/customers");

  const customers = await response.json();

  return { customers };
});

export const customerSlice = createSlice({
  name: "customers",
  initialState: { value: [], loading: loadingStatus.idle },
  reducers: {
   // ...
  },
  extraReducers: (builder) => {
    // Add reducers for additional action types here, and handle loading state as needed
    builder.addCase(loadCustomers.fulfilled, (state, action) => {
      state.value.push(action.payload.customers);
      state.loading = loadingStatus.succeeded
    })
  },
})

相关问题