为什么 Redux 操作没有在 Redux-Toolkit 中被调度

Why Redux action is not Being being dispatched in Redux-Tooklit

我正在使用带有 redux 和 redux-toolkit 的 react-redux。根据这个 example,我创建了一个异步调度,它在解析时调用 reducer 动作。

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

export const BlogSlice = createSlice({
  name: "Blog",
  initialState: {
    BlogList: null,
  },
  reducers: {
    getBlogList: (state, action) => {
      console.log(action.payload);
      state.BlogList = action.payload;
    }
  },
});

export const { getBlogList } = BlogSlice.actions;

export const getBlogListAsync = (user_id) => (dispatch) => {
  axios.get(`/api/blog/getblogs/${user_id}`).then((res) => {
    console.log(res.data);
    dispatch(getBlogList(res.data.result));
  });
};

export const selectBlogList = (state) => state.Blog.BlogList;
export default BlogSlice.reducer;

我相应地在组件中使用了它,以便组件分派 getBlogListAsync 并记录 res.data 但未分派 getBlogList。我尝试输入其他 console.log() 但不明白哪里出了问题。

类似的 Slice 与另一个组件完美配合。

很难确定这里出了什么问题,因为没有什么是绝对错误的。

res.data.result?

您正在登录 res.data,然后将博客列表设置为 res.data.result。我对你的错误的最佳猜测是 res.data.result 不是访问博客的正确 属性,但如果没有看到你的 API.[=17=,我不可能知道这一点]

console.log(res.data);
dispatch(getBlogList(res.data.result));

缺少中间件?

有没有可能没有安装“thunk”中间件?如果您使用 Redux Toolkit 并完全省略中间件,则默认安装 thunk 中间件。此外,如果是这种情况,您应该会收到明显的错误,而不仅仅是什么都没发生。

好像还不错...

我用占位符 API 测试了你的代码,我能够让它正常工作。也许这段代码可以帮助您最终确定问题。 Code Sandbox Demo.

import React from "react";
import { createSlice, configureStore } from "@reduxjs/toolkit";
import axios from "axios";
import { Provider, useDispatch, useSelector } from "react-redux";

export const BlogSlice = createSlice({
  name: "Blog",
  initialState: {
    BlogList: null
  },
  reducers: {
    getBlogList: (state, action) => {
      console.log(action.payload);
      state.BlogList = action.payload;
    }
  }
});

export const { getBlogList } = BlogSlice.actions;

const store = configureStore({
  reducer: {
    Blog: BlogSlice.reducer
  }
});

export const getBlogListAsync = (user_id) => (
  dispatch: Dispatch
) => {
  // your url `/api/blog/getblogs/${user_id}`
  const url = `https://jsonplaceholder.typicode.com/posts?userId=${user_id}`; // placeholder URL
  axios.get(url).then((res) => {
    console.log(res.data);
    // your list: res.data.result <-- double check this
    const list = res.data; // placeholder list
    dispatch(getBlogList(list));
  });
};

export const selectBlogList = (state) => state.Blog.BlogList;

const Test = () => {
  const dispatch = useDispatch();
  const blogs = useSelector(selectBlogList);

  const user_id = "1";

  return (
    <div>
      <button onClick={() => dispatch(getBlogListAsync(user_id))}>
        Load Blogs
      </button>
      <h3>Blog Data</h3>
      <div>{JSON.stringify(blogs)}</div>
    </div>
  );
};

export default function App() {
  return (
    <Provider store={store}>
      <Test />
    </Provider>
  );
}