我正在使用AsyncStorage尝试在我的React应用中持久化我的redux状态,但是我遇到了这个错误:TypeError: undefined is not a function (near '...state.reduce...')。
我查看了其他类似错误的答案,但没有成功。我甚至不确定哪个是undefined,因为它只是说“near”。我已经检查了state对象,它不是空的。
这是我的主要代码:
应用程序.js:
import Main from "./src/components/Main"
import { NativeRouter } from "react-router-native"
import { createStore } from "redux"
import { Provider } from "react-redux"
import reducer from "./src/reducer"
import AsyncStorage from "@react-native-async-storage/async-storage"
import { persistStore, persistReducer } from "redux-persist"
import { PersistGate } from "redux-persist/integration/react"
import Text from "./src/components/Text"
const persistConfig = {
key: "root",
storage: AsyncStorage,
}
const persistedReducer = persistReducer(persistConfig, reducer)
const store = createStore(persistedReducer)
const persistor = persistStore(store)
export default function App() {
return (
<NativeRouter>
<Provider store={store}>
<PersistGate loading={<Text>Loading...</Text>} persistor={persistor}>
<Main />
</PersistGate>
</Provider>
</NativeRouter>
)
}
这是reducer的代码: 减速器.js:
const reducer = (state = [], action) => {
switch (action.type) {
case "NEW_NOTE": {
console.log("state :>> ", state)
const max = state.reduce(
(prev, current) => {
// if (!current) return prev
return current.id > prev.id ? current : prev
},
{ id: 0, body: "" }
)
const newNote = { id: max.id + 1, body: "" }
return state.concat(newNote)
}
case "UPDATE_NOTE": {
const newNotes = state.filter((note) => action.data.id !== note.id)
return [action.data, ...newNotes]
}
case "DELETE_NOTE": {
return state.filter((note) => action.id !== note.id)
}
default: {
return state
}
}
}
export default reducer
持久化的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}}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
为什么会出现TypeError错误?
你遇到了这个错误
TypeError: undefined is not a function (near '...state.reduce...'),因为state不是一个数组,而是一个对象对象没有
reduce方法为什么
react-persist会把你的数组转换成对象?在
react-persist源代码的这一行中,你可以看到let { _persist, ...rest } = state || {}。像这样展开数组会导致它被转换成对象。这是一个bug吗?
可能是的,我在文档中找不到状态必须是对象的任何信息。
如何修复它?
要么将你的状态包装在一个对象中,而不是直接使用数组
要么每次使用时将对象转换回数组