2

我有以下代码:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { client } from '../../api/client';

const initialState = {
    logBook: [],
    status: 'idle',
    error: null
};

export const logNewEntry = createAsyncThunk(
    'logBook/addNewEntry', 
    async (logEntry) => {
        const response = await client.post('/testPost', logEntry);
        console.log('post done');
        return response.data;
    }
);

const logBookSlice = createSlice({
  name: 'logBook',
  initialState,
  // non async calls
  reducers: {},
  },
  // async calls
  extraReducers: {
    [logNewEntry.fulfilled] : (state, action) => {
        console.log('add to list');
        console.log(state);
        console.log(action);
        state.logBook.push(action.payload);
    },
  },
})

//export const {resetName} = logBookSlice.actions;
export default logBookSlice.reducer;

export const selectLogBook = (state) => state.logBook.logBook;

没有引用日志的console.log(state);状态,因此我无法向其中添加新条目。什么控制台打印:

Proxy {i: 0, A: {…}, P: false, I: false, D: {…}, …}
[[Handler]]: null
[[Target]]: null
[[IsRevoked]]: true

我以减少模板的 counterSlice 为例来构建它,以及他们的作品。

    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },

我究竟做错了什么?

4

1 回答 1

5

Redux Toolkit 在createSlice. Immer 将您的原始数据包装在 Proxy 对象中,以便它可以跟踪尝试的“突变”。

不幸的是,这确实使记录草稿状态变得困难,因为浏览器以几乎不可读的格式显示代理。

该行state.logbook.push(action.payload)应按原样有效。但是,如果您想以更具可读性的方式记录数据,可以使用current我们从 RTK 导出的 Immer 方法,该方法将 Proxy 包装的数据转换回纯 JS 对象:

console.log(current(state))

请参阅https://redux-toolkit.js.org/api/other-exports#current

于 2020-12-04T22:37:08.637 回答