Redux devtools显示未定义的状态,但渲染完美

kwvwclae  于 2023-10-19  发布在  其他
关注(0)|答案(2)|浏览(99)

我现在正在尝试Redux Toolkit,因为我一直在我的React应用程序中使用以前的Redux方法。因此,在设置好所有内容并获取数据之后,我的浏览器中的Redux DevTools在状态选项卡中显示undefined。但动作选项卡显示的类型,有效载荷和Meta完美。数据也被完美地呈现出来,没有任何问题。
操作选项卡如下所示:

这是状态选项卡:

不是应该把所有的数据都填进去吗?为什么是undefined?
代码如下:
productSlice.js

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import productService from './productService';

const initialState = {
    products: null,
    isError: false,
    isSuccess: false,
    isLoading: false,
    message: ''
}

// Fetch Products 
export const getProducts = createAsyncThunk('product/getAllProducts', async (thunkAPI) => {
    try {
        return await productService.getAllProducts();
    } catch (error) {
        const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
        return thunkAPI.rejectWithValue(message);
    }
})

export const productSlice = createSlice({
    name: 'product',
    initialState,
    reducers: {
        reset: (state) => {
            state.isLoading = false;
            state.isSuccess = false;
            state.isError = false;
            state.message = ''
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(getProducts.pending, (state) => {
                state.isLoading = true;
            })
            .addCase(getProducts.fulfilled, (state, action) => {
                state.isLoading = false;
                state.isSuccess = true;
                state.products = action.payload.data;
            })
            .addCase(getProducts.rejected, (state, action) => {
                state.isLoading = false;
                state.isError = true;
                state.message = action.payload.message;
                state.products = null;
            })
    }
});

export const { reset } = productSlice.actions;
export default productSlice.reducer;

productService.js

import axios from 'axios';

const API_URL = '/api/products';

const getAllProducts = async () => {
    const response = await axios.get(API_URL);
    return response.data;
}

const productService = {
    getAllProducts
}

export default productService;

store.js

import { configureStore } from "@reduxjs/toolkit";
import productReducer from './product/productSlice';

const store = configureStore({
    reducer: {
        products: productReducer
    }
});

export default store;
fhg3lkii

fhg3lkii1#

看起来你在商店中注册了错误的切片。存储中有“getProducts”切片名称而不是“product”。

oxcyiej7

oxcyiej72#

我只是删除devtool扩展并重新安装它,它对我有效:)

相关问题