我在后端(mySQL)和前端之间渲染数据时遇到了问题。我已经在redux devtools和控制台日志中进行了调试,但仍然找不到原因。数据在控制台日志中正确获取,但当我记录我的状态时,它只是空的。在redux devtools中,我可以在操作选项卡中看到数据,并且状态从待定变为已完成。然而,当它完成时,状态就是空的。
这是我的切片组件的初始状态:
const initialState = {
loading: false,
error: "",
supplierInfo: [
{
id: "",
supplierName: "",
supplierTin: "",
supplierAddress: "",
telNumber: "",
celNumber: "",
emailAddress: "",
},
],
};
这是我的获取函数(数据被正确记录):
export const fetchSuppliers = createAsyncThunk(
"/supplier/fetchSuppliers",
async () => {
try {
const response = await axios.get("http://localhost:3000/api/get");
return response.data;
} catch (error) {
throw error;
}
}
);
这是我的切片代码:
export const SupplierSlice = createSlice({
name: "supplier",
initialState,
reducers: {
addSupplier: (state, action) => {
state.supplierInfo.push(action.payload);
},
extraReducers: (builder) => {
builder.addCase(fetchSuppliers.pending, (state) => {
state.loading = true;
});
builder.addCase(fetchSuppliers.fulfilled, (state, action) => {
state.loading = false;
state.supplierInfo = action.payload;
state.error = "";
});
builder.addCase(fetchSuppliers.rejected, (state, action) => {
state.loading = false;
state.supplierInfo = [];
state.error = action.error.message;
});
},
},
});
export default SupplierSlice.reducer;
export const { addSupplier } = SupplierSlice.actions;
我用于分发数据的代码:
export const SuppliersTable = () => {
const suppliers = useSelector((state) => state.supplier.supplierInfo);
console.log(suppliers);
const data = suppliers;
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchSuppliers());
}, [dispatch]);
上面的console.log只是空的。我不知道为什么。也许问题在reducers中?尽管我可以在操作选项卡中看到数据,但它没有显示到状态中。
这是redux devtools中的操作选项卡:
在此输入图像描述这是状态选项卡中的内容:
在此输入图像描述如您所见,状态中没有显示任何内容。我不知道为什么。有人可以帮忙吗?谢谢!
我已经尝试了几个小时的调试。使用日志语句,redux devtools。我从后端看到了数据,但它没有在状态中。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
Redux状态未接收到数据,因为您的代码语法有误。
请将我的示例代码与您的实际代码进行比较。
const supplierSlice = createSlice({ name: "supplier", initialState: initialState, reducers: {}, extraReducers: (builder) => { builder.addCase(fetchSuppliers.pending, (state, action) => { console.log(action); state.loading = true; }); builder.addCase(fetchSuppliers.fulfilled, (state, action) => { state.supplierInfo = action.payload; state.loading = false; }); builder.addCase(fetchSuppliers.rejected, (state, action) => { state.loading = false; }); } });这是示例示例