我正在使用AsyncStorage尝试在我的React应用中持久化我的redux状态,但是我遇到了这个错误:TypeError: undefined is not a function (near '...state.reduce. ..')
。 我查看了其他类似错误的答案,但没有成功。我什至不确定哪个是undefined,因为它只是说“near”。我已经检查了stateobject,它不是空的。 这是我的主要代码: 应用程序.js:
从“./src/components/Main”导入Main 从“react-router-native”导入 { NativeRouter } 从“redux”导入{createStore} 从“react-redux”导入{Provider} 从“./src/reducer”导入减速器 从“@react-native-async-storage/async-storage”导入AsyncStorage 从“redux-persist”导入{ persistStore, persistReducer } 从“redux-persist/integration/react”导入{PersistGate} 从“./src/components/Text”导入文本 常量持久配置 = { 键:“根”, 存储:异步存储, } const persistedReducer = persistReducer(persistConfig, 减速器) const store = createStore(persistedReducer) const persistor = persistStore(存储) 导出默认函数 App() { 返回 ( <本机路由器> <提供商商店={商店}>正在加载...} persistor={persistor}> <主要> > 持久门> 提供商> ) }
这是reducer的代码: 计量器.js:
const reducer = (state = [], action) =>; { 开关(动作.类型){ 案例“NEW_NOTE”:{ console.log(“状态:>>”,状态) const max = 状态.reduce( (上一个,当前)=> { // if (!current) 返回上一个 返回当前.id >上一个 ID ?当前 : 上一个 }, { id:0,正文:“” } ) const newNote = { id: max.id + 1, body: ""; } 返回state.concat(newNote) } 案例“UPDATE_NOTE”:{ const newNotes = state.filter((note) => action.data.id !== note.id) 返回 [action.data, ...newNotes] } 案例“DELETE_NOTE”:{ return state.filter((note) => action.id !== note.id) } 默认: { 返回状态 } } } 导出默认减速器
持久化的reducer将需要将数据库更改为对象。我想我改变我的代码以适应这个。有任何关于为什么会发生这种情况的想法吗?
使用普通reducer的state对象:
[{"body": "Ddtstostksoyoyyxcuj", "id": 2}, {"body": "Ftistldpufipf Hhxgjbv", "id": 1}]
使用持久化reducer的state对象:
{"0": {"body": "my first note", "id": 1}, "1": {"body": "my second note", "id": 2}, "2": {"body": "my third note", "id": 3}}
减速器.js
const reducer = (state = [], action) => { state = Object.values(state) ...
选择器:
const notes = useSelector((state) => Object.values(state).slice(0, -1))
我必须删除第-1个元素,因为persistor包含一个额外的属性: {"0": {"body": "嗨", "id": 7}, "1": {"body": "", "id": 8}, "2": {"body" :“”,“id”:9},“_persist”:{“重新水合”:true,“版本”:-1}}
为什么会出现TypeError错误?
你遇到了这个错误
TypeError: undefined is not a function (near '...state.reduce...')
,因为state
不是一个数组,而是一个对象对象没有
reduce
方法为什么
react-persist
会把你的数组转换成对象?在
react-persist
源代码的这一行中,你可以看到let { _persist, ...rest } = state || {}
。像这样展开数组会导致它被转换成对象。这是一个bug吗?
可能是的,我在文档中找不到状态必须是对象的任何信息。
如何修复它?
要么将你的状态包装在一个对象中,而不是直接使用数组
要么每次使用时将对象转换回数组