UseContext没有迭代

时间:2019-09-24 07:30:28

标签: reactjs react-hooks

我正在尝试使用React Hook useContext达到一个值,但始终出现以下错误:

TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

CartContext.js

import React, {useState, createContext} from 'react';

export const CartContext = createContext();

export const CartProvider = (props) => {
  const [cart, setCart] = useState([]);
  return (
    <CartContext.Provider value={[cart, setCart]}>
      {props.children}
    </CartContext.Provider>
  )
}

我正在尝试从 Cart.js

到达
import React, {useContext} from 'react'
import {CartContext} from '../../pages/contact/CartContext';
import { slide as Menu } from 'react-burger-menu'
import './Cart.css'

export default function Cart() {
    const [cart, setCart] = useContext(CartContext); //This line causes the error
    return (
        <div>
            <Menu right width={350} 
                  isOpen={false} 
                  id={"testi"} className={ "my-menu" } 
                  customBurgerIcon={<i className="fa fa-shopping-cart" aria-hidden="true"/>}
                  burgerButtonClassName={ "cartButton" }>
                      <h1>Hello</h1>
                  </Menu>  
        </div>
    )
}

1 个答案:

答案 0 :(得分:1)

似乎还好。看到此CodeSandbox:

https://codesandbox.io/s/eager-brattain-2zhxj

index.js

import React from "react";
import ReactDOM from "react-dom";
import Cart from "./Cart";
import { CartProvider } from "./CartContext";

import "./styles.css";

function App() {
  return (
    <CartProvider>
      <Cart />
    </CartProvider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

CartContext.js

import React, { useState, createContext } from "react";

export const CartContext = createContext();

export const CartProvider = props => {
  const [cart, setCart] = useState(["a", "b"]);
  return (
    <CartContext.Provider value={[cart, setCart]}>
      {props.children}
    </CartContext.Provider>
  );
};

Cart.js

import React, { useContext } from "react";
import { CartContext } from "./CartContext";

function Cart() {
  const [cart, setCart] = useContext(CartContext);

  function updateCart() {
    setCart(prevState => {
      const newState = Array.from(prevState);
      newState.push("c");
      return newState;
    });
  }

  return (
    <React.Fragment>
      <div>I am Cart</div>
      <div>Cart value: {JSON.stringify(cart)}</div>
      <button onClick={updateCart}>Add 'c' to cart</button>
    </React.Fragment>
  );
}

export default Cart;