gpt4 book ai didi

reactjs - react & 归还 - "Actions must be plain objects"

转载 作者:行者123 更新时间:2023-12-04 03:15:37 27 4
gpt4 key购买 nike

我想弄清楚为什么这不起作用。

我在 Typescript 上使用 React 和 Redux。

我有以下代码:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {Action} from 'redux';

/** Redux Action **/
class AddTodo implements Action {
type: string;
id: number;
text: string;
constructor(id: number, text: string) {
this.type = 'ADD_TODO';
this.id = id;
this.text = text;
}
}

// ...

class TodoApp extends React.Component {
public render(): JSX.Element {
return (
<div>
<button onClick={() => {
store.dispatch(new AddTodo(0, 'Test'));
}}>
Add Todo
</button>
</div>
);
}
}

// ...

当我点击按钮时,控制台出现以下错误:

Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

我不明白为什么 Redux 假设这是一个异步操作或一个复杂对象。

我的 reducer 甚至没有被执行。它们看起来像这样:

const todoReducer: Reducer<Todo> = (state: Todo, action: Action): Todo => {
if (action instanceof AddTodo)
return { id: action.id, text: action.text, completed: false } as Todo;
// ...
else
return state;
};

const todosReducer: Reducer<Todo[]> = (state: Todo[] = [], action: Action): Todo[] => {
if (action instanceof AddTodo)
return [...state, todoReducer(undefined, action)];
// ...
else
return state;
}

如果我传入 { type: 'ADD_TODO', id: 0, text: 'Test' } 而不是 new Action(0, 'Test'),然后错误消失了,但是由于 reducer 上的条件,我的操作没有正确执行。

你知道这里发生了什么吗?

最佳答案

这是 Dan Abramov 自己解释的:

https://github.com/reactjs/redux/issues/992

基本上,如果使用我的方法,操作的序列化和反序列化(记录/重播功能)将不起作用,因为类型信息不会持久化。

引用丹的话:

In other words, this is an anti-pattern:

function reducer(state, action) {
if (action instanceof SomeAction) {
return ...
} else {
return ...
}
}

If we make it possible for TypeScript users, I know JavaScript users will be tempted and will abuse this because many people coming from traditional OO languages are used to writing code this way. Then they will lose benefits of record/replay in Redux.

One of the points of Redux is to enforce some restrictions that we find important, and that, if not enforced, don't allow for rich tooling later on. If we let people use classes for actions, they will do so, and implementing something like redux-recorder will be impossible because there's no guarantee people use plain object actions. Especially if boilerplate projects suddenly decide to adopt classes because “wow, it’s allowed now, it must be a great idea”.

关于reactjs - react & 归还 - "Actions must be plain objects",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41302409/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com