状态没有在减速器内更新? redux/工具包

问题描述 投票:0回答:1

我正在为我的项目使用 redux 工具包,我有一个问题,我使用 reduxjs 提供的当前函数访问减速器内的状态 但是当我更新状态时,它没有更新,我不知道为什么我对此做了很多研究,但我没有发现任何有用的东西,这是我的减速器

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

const initialState = {
  posts: [],
};

const postSlice = createSlice({
  name: "posts",
  initialState,
  reducers: {
    updatePosts: (state, action) => {
      const postsArray = Object.values(action.payload);
      // state.posts = state.posts.concat(Object.values(action.payload));
      state.posts.push(...postsArray);
    },
    updateLikes: (state, action) => {
      const { postId, userId } = action.payload;
      const currentState = current(state.posts)

    },
  },
});

export const { updatePosts, updateLikes } = postSlice.actions;
export default postSlice.reducer;

在 updateLikes 中,我正在获取 postId 和 userId,当我使用调度时,我会成功获取它们。但是当我使用当前函数获取当前状态时,它也会返回状态,但是当我尝试从数组中推送或删除任何内容时,什么也没有发生,也没有显示任何错误或其他任何内容

reactjs redux react-redux redux-toolkit
1个回答
0
投票
RTK 的

current
函数用于获取状态快照以用于只读目的。因此,要修改
updateLikes
减速器中的状态,您应该直接修改状态,例如:

updateLikes: (state, action) => {
  const { postId, userId } = action.payload;
  const post = state.posts.find(post => post.id === postId);
  // Any logic connected to post update, like post.likes = ...
},
© www.soinside.com 2019 - 2024. All rights reserved.