React Native异步存储类型错误:undefined不是函数(靠近“...state.reduce ...”)

ygya80vv  于 2023-01-31  发布在  React
关注(0)|答案(1)|浏览(157)

我正在使用AsyncStorage尝试在React应用中持久化redux状态,但收到以下错误:TypeError: undefined is not a function (near '...state.reduce...')。我已经查看了类似错误的其他答案,但没有运气。我甚至不确定什么是未定义的,因为它只是说"near"。我已经检查了状态对象,它不是空的。下面是我的主要代码:App.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正在将数组更改为对象。我想我需要更改代码来适应这种情况。知道为什么会发生这种情况吗?
所述物体具有正常大小:

[{"body": "Ddtstostksoyoyyxcuj", "id": 2}, {"body": "Ftistldpufipf 
Hhxgjbv", "id": 1}]

具有持久化Reducer状态对象:

{"0": {"body": "my first note", "id": 1}, "1": {"body": "my second note", "id": 2}, "2": {"body": "my third note", "id": 3}}
rryofs0p

rryofs0p1#

为什么是类型错误?

您会得到这个错误TypeError: undefined is not a function (near '...state.reduce...'),因为state不是一个数组,它是一个对象
对象没有reduce方法

为什么react-persist将数组转换为对象?

在这行react-persist源代码中,你可以看到let { _persist, ...rest } = state || {}。像这样扩展数组会导致它被转换成一个对象。

是一个错误吗?

也许,我在文档中找不到状态必须是对象的任何地方。

如何修复?

将状态 Package 在对象中,而不是直接使用数组
或者在每次要使用对象时将其转换回数组

相关问题