数据未存储在 redux 存储中

Data is not being stored in redux store

store image我打算将数据存储到 react-redux-store 但它没有被存储。我不明白我错过了什么......我在下面给出了我的代码。

我正在尝试存储来自 api 的数据,但它不起作用...

INDEX.JS

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import { store } from "./features/store";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

STORE.JS

import { configureStore } from "@reduxjs/toolkit";
import moviesReducer from "./movies/movieSlice";

export const store = configureStore({
  reducer: moviesReducer,
});

电影SLICE.JS

import { createSlice } from "@reduxjs/toolkit";

const initialstate = {
  movies: [],
};

const movieSlice = createSlice({
  name: "movies",
  initialstate,
  reducers: {
    addMovies: (state, { payload }) => {
      state.movies = payload;
    },
  },
});

export const { addMovies } = movieSlice.actions;
// export const getAllMovies = (state) => state.movies.movies;
export default movieSlice.reducer;

组件

import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import MovieAPI from "../config/MovieAPI";
import { addMovies } from "../features/movies/movieSlice";

const Home = () => {
  const dispatch = useDispatch();

  const fetchMovies = async () => {
    const response = await MovieAPI.get(`?apiKey=1234&s=harry&type=movie`);
    console.log(response.data);
    dispatch(addMovies(response.data));
  };

  useEffect(() => {
    fetchMovies();
  }, []);

return 新状态:

    addMovies: (state, { payload }) => ({
      ...state, 
      movies: payload
    }),

顺便说一句,你怎么知道它没有存储。请显示您使用状态数据呈现某些组件的代码。

对于第一个:createSlice 希望收到名为 initialState 而不是 initialstate 的 属性 对象,请注意驼峰式命名。

下一个:根据位置和切片名称“电影”我可能怀疑你应该将它定义为:const initialState = [];,因为它是“电影切片”初始状态定义本身,否则你将有状态类似 state = {movies: {movies: []}}.

此外,您可能希望重写 addMovies reducer,如:

    addMovies: (moview_slice_state, { payload }) => {
      console.log("add movies", payload);
      moview_slice_state.push(...payload);
    }

其中 moview_slice_state - 整个状态的 movies 切片的状态,例如state.movies.

顺便说一句,由于 @reduxjs/toolkit use immer 在幕后,您可以“修改”状态 return 新状态,正如 Andrej Kirejeŭ 所建议的。但不是他们两个。

P.S。对于未来,请随时为您的问题或答案创建最小的演示,例如 live demo 基于您的代码