在登录到控制台而不是 reducer 操作中的 Proxy 对象时如何查看状态?

How do I see state when logging to the console instead of Proxy object inside reducer action?

在 reducer 操作中使用 console.log() 时,状态打印为 Proxy 对象,而不是我真正想看到的对象。我如何看到实际对象?我用的是redux-starter-kit createSlice,不知道跟这个有没有关系

import { createSlice } from "redux-starter-kit";

export interface IToDo {
    id: number;
    name: string;
    complete: boolean;
}

const initialState: IToDo[] = [
    {
        id: 1,
        name: 'Read a bit',
        complete: true
    }
];

const { actions, reducer } = createSlice({
    slice: "todos",
    initialState,
    reducers: {
        toggleTodo(state: IToDo[], action) {
            const todo = state.find(todo => todo.id === action.payload);
            console.log(todo);
            if (todo) {
                todo.complete = !todo.complete;
            }
        }
    }
})

export const toDosReducer = reducer;
export const { toggleTodo } = actions;

这是我在切换 ToDo 时在控制台中看到的输出:

您可以将您的对象转换为带有缩进数的字符串,检查下面的代码:

JSON.stringify(state, undefined, 2)

它returns像这样

// { 
//   "firName: "..."
//   "lastName": '...',     
//   ... 
// }

Redux 工具包包含专门用于此目的的 immer current 函数。您可以拨打:

console.log(current(state))

根据 redux toolkit docs

The current function from the immer library, which takes a snapshot of the current state of a draft and finalizes it (but without freezing). Current is a great utility to print the current state during debugging, and the output of current can also be safely leaked outside the producer.

immer docs 中有更多信息。