未捕获的TypeError:将useReducer与useContext一起用于全局存储React js时对象不可迭代

问题描述

我正在尝试使用钩子将redux存储替换为动作和reducer 我已经使用createContext创建了一个全局存储,并使用useReducer创建了一个全局化简器,并尝试在下面的文件中将useState和全局状态对象一起使用,这会引发错误。另外,我尝试过控制台记录useContext(Store)的返回值,该值给出了未定义的值。

import React,{useContext,useEffect} from 'react'
import {newAction} from './actions'
import Store from '../../utils/store'
const Home = ()=>{
    console.log(Store)
    const [appStore,dispatch] = useContext(Store)
    useEffect(()=>{
        
        dispatch(newAction())
        console.log(appStore)
    },[]) 
    return(<div>Hello there</div>)
}

export default Home

在第index.jsx:7 Uncaught TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) at Home (index.jsx:7) at renderWithHooks (react-dom.development.js:14803)行出现错误const [appStore,dispatch] = useContext(Store)

我的 App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Home from './pages/home';
import './styles/index.scss'
import {StoreProvider} from './utils/store'

function App() {
  return (
    <div className="App">
    <StoreProvider>
      <Home/>
    </StoreProvider>
    
    </div>
  );
}

export default App;

我的 Store / index.js

import {createContext} from 'react'

const Store = createContext({});

export const StoreProvider = Store.Provider;

export default Store;

contextProvider.js

import React,{useReducer} from 'react';
import {ContextProvider} from './index'
import reducer from './combineReducer'

const initialState = { home:{} }

const StoreProvider = (props) =>{
    return <ContextProvider value={useReducer(reducer,initialState)}>
        {props.children}
    </ContextProvider>
}
export default StoreProvider

combineReducer.js

import homeReducer from '../../pages/home/reducer'
export default mainReducer = (initialState,action)=>{
    return({
        home: homeReducer(initialState.home,action)
    })
}

home / reducer.js

import {NEW_ACTION} from './actions'
export default reducer = (state,action) =>{
    switch(action.type){
        case NEW_ACTION: return {...state,val:true}
        default: return state
    }
}

解决方法

以下文件中的代码几乎没有错误:

  1. 在文件 Store / index.js 中将变量StoreProvider重命名为 ContextProvider就像我使用的ContextProvider一样(在此未定义)。
  2. 在文件 App.js 中,因为提供程序是在contextProvider文件中编写的,因此将导入行import {StoreProvider} from './utils/store'更改为import StoreProvider from './utils/store/contextProvider'

修复后的文件:

Store / index.js

import {createContext} from 'react'
const Store = createContext({});
export const ContextProvider = Store.Provider;
export default Store;

App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Home from './pages/home';
import './styles/index.scss'
import StoreProvider from './utils/store/contextProvider'
function App() {
  return (
    <div className="App">
    <StoreProvider>
      <Home/>
    </StoreProvider>
    </div>
  );
}
export default App;