Redux工具包不更新状态

v8wbuo2f  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(122)

即使我成功地从API获取了posts并使用dispatcher将响应保存到状态。国家没有更新。在Feed中,它显示No posts found,但在posts.js中(第11行),它使用posts数组控制台记录状态
第一个月

export default function Feed() {

  const dispatch = useDispatch();
  useEffect(()=>{
    const postsFetch = async () => {
      const res = await fetch("/api/posts?author&likes",{
        headers:{
          "authorization": "Bearer "+user.token,
          "Content-Type":"application/json",
        }
      })
      const data = await res.json();
      dispatch(postActions.setPosts(data))
    }
    postsFetch();
  },[])
  const contextPosts = useSelector(s=>s.posts)
  const user = useSelector(s=>s.user)
  console.log(user)
  console.log(contextPosts)
  return (
    <div class="container pt-4 pb-4">
      {contextPosts.length == 0 && <h5 className="text-muted">No posts found</h5> }
      {contextPosts.map(d=>(
      <Post data={d} />
      ))}
    </div>
  );
}

字符串
posts.js | posts slice

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

let initialState = []

export const postsSlice = createSlice({
  name: "posts",
  initialState,
  reducers: {
    setPosts: (state, action) => {
      state = action.payload;
      console.log(state)
    },
  },
});

// Action creators are generated for each case reducer function
export const postActions = postsSlice.actions;

export default postsSlice.reducer;

brjng4g3

brjng4g31#

在Redux-Toolkit状态片缩减器中,你应该 mutate 状态对象*或者**返回 * 下一个状态对象引用(但不是两者都是)。reducer代码的问题是,您只是重新分配了状态引用。有关更多详细信息,请参见直接状态突变。
示例如下:

const initialState = {
  property: { ... }
};

字符串

  • 改变状态引用
export const stateSlice = createSlice({
  name: "state",
  initialState,
  reducers: {
    stateAction: (state, action) => {
      state.property = action.payload;
    },
  },
});

  • 返回新的状态引用
export const statesSlice = createSlice({
  name: "state",
  initialState,
  reducers: {
    stateAction: (state, action) => {
      return {
        ...state,
        property: action.payload;
      };
    },
  },
});


由于postSlice中的状态是一个数组,所以你不能改变它,所以你将 * 返回 * action.payload * 作为 * 下一个状态。

export const postsSlice = createSlice({
  name: "posts",
  initialState,
  reducers: {
    setPosts: (state, action) => {
      return action.payload;
    },
  },
});


您还应该记住,在RTK切片缩减器中,您正在编辑状态的草稿副本,因此尝试console.log(state)不会记录状态,而是记录您正在编辑的草稿代理对象。如果你想记录中间状态的变化,那么使用current,它是从immer库中重新导出的current函数。请参见记录拔模状态值。
示例如下:
动作

{
  payload: "bar"
}
import { current } from '@reduxjs/toolkit';

const initialState = {
  property: "foo"
};

...

stateAction: (state, action) => {
  console.log(current(state)); // { property: "foo" }
  state.property = action.payload;
  console.log(current(state)); // { property: "bar" }
},

的字符串

相关问题