猿问

Redux-toolkit:状态是 createSlice 减速器内的代理

我正在尝试在切片减速器内的状态数组中追加/更新一些数据,但是当我尝试对我感兴趣的状态数组进行操作时,我只得到了一个 javascript 代理console.log。.projects这是怎么回事(我做错了什么)?


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


const initialState = {

  projects: [],

};


const projectsSlice = createSlice({

  name: 'projectsSlice',

  initialState: { ...initialState },

  reducers: {

    addProject(state, action) {

      const { project } = action.payload;

      const newProjects = [project, ...state.projects];


      console.group('add project');

      console.log('project: ', project);

      console.log('state projects: ', state.projects);

      console.log('newProjects: ', newProjects);

      console.groupEnd();


      state.projects = newProjects;

    },

    setProjects(state, action) {

      const { projects } = action.payload;

      state.projects = projects;

    },

    removeProject(state, action) {

      const { projectId } = action.payload;

      const newProjects = [...state.projects].filter((project) => project.id !== projectId);

      state.projects = newProjects;

    },

    updateProject(state, action) {

      const { project } = action.payload;

      const projectIndex = state.projects.findIndex((stateProject) => stateProject.id === project.id);

      const newProjects = [...state.projects].splice(projectIndex, 1, project);


      console.group('updateProject');

      console.log('project: ', project);

      console.log('projectIndex: ', projectIndex);

      console.log('state projects: ', state.projects);

      console.log('newProjects: ', newProjects);

      console.groupEnd();


      state.projects = newProjects;

    },

  },

});


export const { addProject, removeProject, updateProject, setProjects } = projectsSlice.actions;


export default projectsSlice.reducer;


元芳怎么了
浏览 125回答 2
2回答

慕标琳琳

代理是您可以在该减速器中改变状态并在您的状态中获得不可变副本的原因 - 但浏览器在记录代理方面确实很糟糕。根据文档,您可以使用currentRTK&immer 的导出:const slice = createSlice({  name: 'todos',  initialState: [{ id: 1, title: 'Example todo' }],  reducers: {    addTodo: (state, action) => {      console.log('before', current(state))      state.push(action.payload)      console.log('after', current(state))    },  },})

慕娘9325324

您需要使用当前import { current } from '@reduxjs/toolkit'这样,您就可以达到当前状态并使用它们,之后,您可以在减速器中发送返回以返回新数据。威尔看起来像这样:const referralSlicer = createSlice({name: 'referral',initialState: {  referrals: [],  currentCard: 0,} as IReferralSlicer,reducers: {  addReferrals(state, { payload }) {    return {      referrals: [...state.referrals, payload],    }  },  deleteReferral(state, { payload }) {    const currentState = current(state)    return {      ...currentState,      referrals: currentState.referrals.splice(payload, 1),    }  },  setCurrentCard(state, { payload }) {    return {      referrals: state.referrals,      currentCard: payload,    }  },},})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答