我有一个简单的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
1条答案
按热度按时间9w11ddsr1#
初始状态是从Web服务器加载数据之前的状态,所以我假设它应该是一个空Array或
undefined
:您可能需要确保客户已加载并在加载时显示动画。因为Web服务器可能会在20秒后返回响应。
因此,您的初始状态可能会变成:
另一种方法是使用createAsyncThunk中建议的状态变量
因此,在您的示例中,结果将是: