React createSlice 的 extraReducers 的状态访问

Han*_*Lin 2 reactjs redux react-redux redux-reducers

我有以下代码:

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;
Run Code Online (Sandbox Code Playgroud)

console.log(state);未引用航海日志的状态,为此我可以在新的条目不添加到它。什么控制台打印:

Proxy {i: 0, A: {…}, P: false, I: false, D: {…}, …}
[[Handler]]: null
[[Target]]: null
[[IsRevoked]]: true
Run Code Online (Sandbox Code Playgroud)

我使用reduc 模板的counterSlice 作为示例来构建它,以及它们的工作。

    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

mar*_*son 5

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

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

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

console.log(current(state))
Run Code Online (Sandbox Code Playgroud)

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

  • 这不是 Redux 的问题,而是你如何在 React 组件中渲染的问题。React 不会让你做`<div>{someObject}</div>`。您只能将原始值作为 JSX 输出中的变量传递,例如“<div>{someObject.name}</div>”。修复渲染逻辑将解决该错误。 (2认同)