代码之家  ›  专栏  ›  技术社区  ›  Zak

Redux devtools显示未定义的状态,但呈现完美

  •  1
  • Zak  · 技术社区  · 3 年前

    我现在正在试用Redux工具包,因为我在React应用程序中使用了之前的Redux方法。因此,在设置所有内容并获取数据后,我的浏览器中的Redux DevTools会显示 undefined 在状态选项卡中。但action选项卡完美地显示了类型、负载和元数据。数据也被完美呈现,没有任何问题。

    以下是“操作”选项卡的外观:

    enter image description here

    这是状态标签:

    enter image description here

    它不是应该被所有的数据填充吗?为什么它没有定义?

    以下是代码:

    产品切片。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;
    

    产品服务。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;
    

    百货商店js

    import { configureStore } from "@reduxjs/toolkit";
    import productReducer from './product/productSlice';
    
    const store = configureStore({
        reducer: {
            products: productReducer
        }
    });
    
    export default store;
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   kriss    3 年前

    看起来你在商店里注册的这一片不正确。商店中有“getProducts”切片名称,而不是“product”。