我正在尝试切换我正在构建的应用程序以使用 Redux Toolkit,并注意到当我从 createStore 切换到 configureStore 时出现此错误:
A non-serializable value was detected in the state, in the path: `varietals.red.0`. Value:, Varietal {
"color": "red",
"id": "2ada6486-b0b5-520e-b6ac-b91da6f1b901",
"isCommon": true,
"isSelected": false,
"varietal": "bordeaux blend",
},
Take a look at the reducer(s) handling this action type: TOGGLE_VARIETAL.
(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)
在四处寻找之后,我发现问题似乎出在我的自定义模型上。例如,品种数组是从品种模型创建的:
class Varietal {
constructor(id, color, varietal, isSelected, isCommon) {
this.id = id;
this.color = color;
this.varietal = varietal;
this.isSelected = isSelected;
this.isCommon = isCommon;
}
}
并使用它映射到一个字符串数组来创建我的 Varietal 数组,该数组进入我的状态:
// my utility function for creating the array
const createVarietalArray = (arr, color, isCommon) =>
arr.map(v => new Varietal(uuidv5(v, NAMESPACE), color, v, false, isCommon));';
// my array of strings
import redVarietals from '../constants/varietals/red';
// the final array to be exported and used in my state
export const COMMON_RED = createVarietalArray(redVarietals.common.sort(), 'red', true);
当我切换出模型并将数组创建实用程序替换为返回对象的普通数组时,如下所示:
export const createVarietalArray = (arr, color, isCommon) =>
arr.map(v => ({
id: uuidv5(v, NAMESPACE),
color,
varietal: v,
isSelected: false,
isCommon,
}));
然后那个特殊的减速器的错误消失了,但是我在我的应用程序中都有这些自定义模型,在我开始将它们全部撕掉并重新编码它们只是为了能够使用我想在这里问的 Redux 工具包之前在我这样做之前真的是问题所在......