React Native AsyncStorage 오류: TypeError - 정의되지 않음은 함수가 아닙니다("...state.reduce..." 근처).
P粉734486718
P粉734486718 2023-08-29 16:54:51
0
1
541
<p>AsyncStorage를 사용하여 React 앱에서 redux 상태를 유지하려고 하는데 다음 오류가 발생합니다: <code>TypeError: undefine is not a function (near '...state.reduce. ..')</코드>. 비슷한 오류가 있는 다른 답변을 보았지만 성공하지 못했습니다. "near"라고만 표시되어 있기 때문에 어느 것이 정의되지 않은지 확실하지 않습니다.나는 상태가 좋지 않고 공허하지 않습니다. 내 주인님이 말한 대로: 应용程序.js:</p> <pre class="brush:php;toolbar:false;">"./src/comComponents/Main"에서 Main 가져오기 import { NativeRouter } from "react-router-native" "redux"에서 import { createStore }를 가져옵니다. "react-redux"에서 { 제공자 }를 가져옵니다. "./src/reducer"에서 감속기를 가져옵니다. "@react-native-async-storage/async-storage"에서 AsyncStorage를 가져옵니다. "redux-persist"에서 import { persistStore, persistReducer }를 가져옵니다. "redux-persist/integration/react"에서 import { PersistGate }를; "./src/comComponents/Text"에서 텍스트 가져오기 const persistConfig = { 키: "루트", 저장: AsyncStorage, } const persistedReducer = persistReducer(persistConfig, 감속기) const 저장소 = createStore(persistedReducer) const 지속자 = persistStore(저장소) 기본 함수 내보내기 App() { 반품 ( <네이티브라우터> <공급업체 스토어={스토어}> <PersistGate loading={<Text>로드 중...</Text>} persistor={persistor}> <메인 /> </PersistGate> </공급자> </네이티브라우터> ) }</pre> <p>Reducer의 대안: 减速器.js:</p> <pre class="brush:php;toolbar:false;">const 감속기 = (상태 = [], 동작) => { 스위치(action.type) { 사례 'NEW_NOTE': { console.log("state :>> ", state) const 최대 = 상태.감소( (이전, 현재) => { // (!current)인 경우 이전을 반환합니다. 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) } 기본: { 반환 상태 } } } 기본 감속기 내보내기</pre> <h1>编辑</h1> <p>이것은 강력한 감속기입니다.어떤 것이 있나요?</p> <p>이용되는 통신 감속기의 상태는</p> <pre class="brush:php;toolbar:false;">[{"body": "Ddtstostksoyoyyxcuj", "id": 2}, {"body": "Ftistldpufipf Hhxgjbv', 'id': 1}]</pre> <p>使用持久化reducer의 상태对象:</p> <pre class="brush:php;toolbar:false;">{"0": {"body": "내 첫 번째 메모", "id": 1}, "1": { "body": "내 두 번째 메모", "id": 2}, "2": {"body": "내 세 번째 메모", "id": 3}}</pre> ;

修复

<p>减速器.js</p> <pre class="brush:php;toolbar:false;">const 감속기 = (상태 = [], 동작) => { 상태 = Object.values(상태) ...</pre> <p>选择器:</p> <pre class="brush:php;toolbar:false;">const Notes = useSelector((state) => Object.values(state).slice(0, -1))</pre> <p>저희는 1만 달러의 지속성 저항을 가지고 있습니다. <code>{"0": {"body": "嗨", "id": 7}, "1": {"body": "", "id": 8}, "2": {" body" :“”,“id”:9},“_persist”:{“중신수합”:true,“版本”:-1}}</code></p>
P粉734486718
P粉734486718

모든 응답(1)
P粉111927962

TypeError는 왜 발생하나요?

이 오류가 발생했습니다TypeError: undefined is not a function (near '...state.reduce...'),因为state배열이 아니라 객체입니다

객체에는 reduce메서드

가 없습니다.

react-persist배열을 객체로 변환하나요?

react-persist源代码的这一行中,你可以看到let { _persist, ...rest } = state || {} 소스 코드 이 줄 a>, let { _persist, ...rest } = state {}를 볼 수 있습니다. 이와 같이 배열을 펼치면 객체로 변환됩니다.

이거 버그인가요?

아마도 그렇습니다. 문서에서 상태가 객체여야 한다는 정보를 찾을 수 없습니다.

어떻게 고치나요?

배열을 직접 사용하는 대신 객체에 상태를 래핑하세요

또는 사용할 때마다 객체를 다시 배열로 변환하세요

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!