redux-toolkit InitialState 没有改变

redux-toolkit InitialState not changing

我的问题是来自 slice.js 的 initialState 没有改变,当我 console.log 存储(使用 UseSelector)时,我看到 state.list 是空的并且没有 changed.I'尝试从 GET 端点捕获数据,端点正在工作。

store.js

import { configureStore } from '@reduxjs/toolkit';
import shopReducer from '../connection/shopSlice';

export const store = configureStore({
    reducer: {
        shop: shopReducer,
    },
    devTools: true
});

slice.js

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

export const getProducts = createAsyncThunk(
    'shop/getProducts',
    async () => {
        const response = await axios.get('http://localhost:3000/products');
        return response.data;
    }
);
export const listOfProducts = createSlice({
    name: 'shop',
    initialState: {
        list: [],
        status: 'idle',
        error: null,
    },
    reducers: {
        addProduct: {
            reducer: (state, action) => {
                state.list.push(action.payload);
            },
            prepare(value) {
                return {
                    payload: {
                        key: value.id,
                        value: value,
                    },
                };
            },
        },
    },
    extraReducers: {
        [getProducts.pending]: (state, action) => {
            state.status = 'loading';
        },
        [getProducts.fulfilled]: (state, action) => {
            state.status = 'succeeded';
            state.list.push(...action.payload);
        },
        [getProducts.rejected]: (state, action) => {
            state.status = 'failed';
            state.error = action.error.message;
        },
    },
});

export const { addProduct } = listOfProducts.actions;

export default listOfProducts.reducer;

组件 console.log

import React from 'react';
import common from './common.module.scss';
import shopCards from './shopCards.module.scss';
import { useSelector } from "react-redux";
const ShopCards = () => {
    console.log(useSelector(state=>state))
    return (
        <div>
        </div>

    );
};
export default ShopCards;

问题是您根本没有分派 getProducts,您应该分派此操作并将 useSelector(state => state.shop) 的状态变为 select 正确的减速器状态。尝试将您的代码更改为以下内容:

import React from 'react';
import common from './common.module.scss';
import shopCards from './shopCards.module.scss';

// Don't forget to change the path
import { getProducts } from './path/to/reducer'
import { useSelector, useDispatch } from "react-redux";
import { useEffect } from "react";

const ShopCards = () => {
    const products = useSelector((state) => {state.shop});

    useEffect(() => {
      // dispatch the action on first render
      useDispatch(getProducts());
    }, []);

    useEffect(() => {
      // print the products if the fetch to backend was made successfully 
      console.log(products);
    }, [products]);

    return (
        <div>
        </div>

    );
};
export default ShopCards;

另外,在您的 createAsyncThunk 中您正在返回 response.data,因此为了正确实现状态,您的 api 响应应如下所示:

{
  // you must return a JSON with data key who has an array of your products
  // the content of product was just an example, so ignore it
  data: [{id: 1, product: "foo"}]
}