[英]React Hook + Context api
I am fairly new to React Hooks and context api.我对 React Hooks 和上下文 api 相当陌生。 I am trying to create a global state management within react (no redux) but I am running into this error.
我正在尝试在 react(无 redux)中创建全局 state 管理,但我遇到了这个错误。
TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
I just started this project and just trying to set up a shopping cart (which will use the global CartItem to keep track of total items)我刚开始这个项目,只是想建立一个购物车(它将使用全局 CartItem 来跟踪总项目)
GlobalStates.jsx (My global state manager file) GlobalStates.jsx(我的全局 state 管理器文件)
import React from 'react';
export const CartContext = React.createContext(0)
const GlobalContextWrapper = (props) => {
const [cartItem,incCartItem] = React.useState(0);
return(
<CartContext.Provider value={[cartItem,incCartItem]}>
{props.children}
</CartContext.Provider>
)
}
export default GlobalContextWrapper
index.js index.js
import React from 'react';
import ReactDOM from 'react-dom';
import GlobalContextWrapper from "./GlobalStates.jsx"
import Test from "./Test.jsx"
const Main = () => {
return(
<GlobalContextWrapper>
<Test/>
</GlobalContextWrapper>
)
}
ReactDOM.render(<Main/>,document.getElementById('root'));
Test.jsx (the file which is trying to access the context global states) Test.jsx(试图访问上下文全局状态的文件)
import React from 'react';
import CartContext from "./GlobalStates"
const Test = () => {
const [cartItem,incCartItem] = React.useContext(CartContext)
return(
<h1>The cart total is {cartItem}</h1>
)
}
export default Test
Your code works just fine, but in Test you need to import the context correctly: import {CartContext} from "./GlobalStates"
您的代码运行良好,但在测试中您需要正确导入上下文:
import {CartContext} from "./GlobalStates"
const CartContext = React.createContext(0); const GlobalContextWrapper = (props) => { const [cartItem, incCartItem] = React.useState(0); return ( <CartContext.Provider value={[cartItem, incCartItem]}> {props.children} </CartContext.Provider> ); }; const Test = () => { const [cartItem, incCartItem] = React.useContext( CartContext ); return <h1>The cart total is {cartItem}</h1>; }; const Main = () => { return ( <GlobalContextWrapper> <Test /> </GlobalContextWrapper> ); }; ReactDOM.render(<Main />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.