React/Redux/Immutable.js - Immutable actions (Error: Actions must be plain objects)
React/Redux/Immutable.js - Immutable actions (Error: Actions must be plain objects)
我正在将 React 与 Redux 结合使用 Immutable.js - 我的状态由不可变对象组成并且工作正常。
现在我正在尝试让我的 actions 不可变对象而不是普通的 Javascript 对象。
我的 reducers 和 action creator 工作并且我的所有单元测试都通过了,但是当我尝试在 React 组件中使用不可变的 action 对象时,我收到一个错误,因为我的 Action 对象是一个不可变的 Map(而不是普通的 javascript对象)。
这是我的操作:
export const cancel = () => {
return Immutable.Map({
type: ACTION_TYPES.get('CANCEL')
})
}
我的 reducer 是这样的(在单元测试时工作,但 React 由于错误从不调用它):
export const site = (state = initialState, action) => {
const actionType = null
try {
action.get('type')
} catch (e) {
return state
}
switch (actionType) {
... so on and so forth ...
这是测试组件时的错误:
FAIL src/App.test.js
● Test suite failed to run
Actions must be plain objects. Use custom middleware for async actions.
我需要添加什么中间件才能让我的 Immutable.js 对象作为动作运行?我在文档中找不到它...
What middleware do I need to add so that my Immutable.js objects work as actions? I cannot find it in the docs...
如果您想构建自定义行为,您需要自己构建中间件。像这样:
import { isImmutable } from 'immutable';
// Allows immutable objects to be passed in as actions. Unwraps them, then
// forwards them on to the reducer (or the next middleware).
const immutableMiddleware = store => next => action => {
if (isImmutable(action)) {
next(action.toJS())
} else {
next(action);
}
};
就是说,我真的看不出将操作作为不可变对象有什么好处。操作通常在需要时立即创建,并且永远不会再次访问,因此保护它免受突变几乎从来不是一个问题。而且您通常不会克隆它们,因此 immutablejs 在从旧对象创建新的不可变对象时提供的性能优势将无法实现。
我正在将 React 与 Redux 结合使用 Immutable.js - 我的状态由不可变对象组成并且工作正常。
现在我正在尝试让我的 actions 不可变对象而不是普通的 Javascript 对象。
我的 reducers 和 action creator 工作并且我的所有单元测试都通过了,但是当我尝试在 React 组件中使用不可变的 action 对象时,我收到一个错误,因为我的 Action 对象是一个不可变的 Map(而不是普通的 javascript对象)。
这是我的操作:
export const cancel = () => {
return Immutable.Map({
type: ACTION_TYPES.get('CANCEL')
})
}
我的 reducer 是这样的(在单元测试时工作,但 React 由于错误从不调用它):
export const site = (state = initialState, action) => {
const actionType = null
try {
action.get('type')
} catch (e) {
return state
}
switch (actionType) {
... so on and so forth ...
这是测试组件时的错误:
FAIL src/App.test.js
● Test suite failed to run
Actions must be plain objects. Use custom middleware for async actions.
我需要添加什么中间件才能让我的 Immutable.js 对象作为动作运行?我在文档中找不到它...
What middleware do I need to add so that my Immutable.js objects work as actions? I cannot find it in the docs...
如果您想构建自定义行为,您需要自己构建中间件。像这样:
import { isImmutable } from 'immutable';
// Allows immutable objects to be passed in as actions. Unwraps them, then
// forwards them on to the reducer (or the next middleware).
const immutableMiddleware = store => next => action => {
if (isImmutable(action)) {
next(action.toJS())
} else {
next(action);
}
};
就是说,我真的看不出将操作作为不可变对象有什么好处。操作通常在需要时立即创建,并且永远不会再次访问,因此保护它免受突变几乎从来不是一个问题。而且您通常不会克隆它们,因此 immutablejs 在从旧对象创建新的不可变对象时提供的性能优势将无法实现。