【问题标题】:Getting this error while using context API. TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))使用上下文 API 时出现此错误。 TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))
【发布时间】:2021-01-31 17:22:00
【问题描述】:

我刚刚尝试使用上下文 api 从另一个组件访问一个变量,它抛出了奇怪的错误。

这是我的父组件。

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

export const CartContext=createContext()    

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

export default CartValue

下面是我的子组件。

import React,{useContext} from 'react'
import CartValue,{CartContext} from './CartValue'


function ChildContext() {
    const [cart,setCart]=useContext(CartContext)
    return (
        <div>
           <h3>{cart}</h3>

        </div>
    )
}

export default ChildContext

以下是我遇到的错误。

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

请解决这个问题。提前致谢

【问题讨论】:

    标签: reactjs react-redux react-context


    【解决方案1】:

    Context API 没有任何问题,您只需将组件包装在其中即可。

    下面是我的解决方案

           <CartValue>
                <ChildContext />
           </CartValue>
    

    【讨论】:

      【解决方案2】:

      您将cart 作为值传递给CartContext.Provider,这意味着您的上下文包含cart 的值,这似乎是一个默认为0 的数字。但是当使用你的上下文时,你把它当作一个由useState 返回的数组。这就是您看到错误Object is not iterable 的原因。这个错误没有什么奇怪的。这只是意味着您尝试迭代不是数组或任何可迭代的东西。

      如果您想这样做,您需要将从useState 返回的所有内容放入上下文中,而不仅仅是状态值:

      const CartValue =(props)=>{
          const cartState = useState(0)
      
          return (
              <CartContext.Provider value={cartState}>
                  {props.children}
              </CartContext.Provider>  
          )
      }
      

      【讨论】:

      • 那么我如何在没有方法的情况下更新 cartState 值?
      • @manee 您目前没有在CartValue 组件中更新它,因此您不需要那里的方法。当您将带有值和更新器函数的整个数组传递到上下文时,您仍然可以在使用上下文的地方更新它。
      • 除了空白屏幕外,我没有得到任何输出
      • 它返回一个未定义的值。我已经通过 console.log() 进行了检查
      • @manee 你如何渲染你的组件?您是否知道您需要将ChildContext 包装成CardValue 才能使其工作?有关工作示例,请参阅此:codesandbox.io/s/ecstatic-shannon-nor48?file=/src/App.js
      【解决方案3】:

      变化:

      const [cart,setCart]=useContext(CartContext)
      

      const cart = useContext(CartContext)
      

      原因是,您在CartContext.Provider value={cart} 中提供的值是一个数字,而不是一个数组。

      【讨论】:

      • 我在教程中看到过这个并尝试过。他说我们可以通过这个上下文 api 发送整个状态
      • 检查this
      猜你喜欢
      • 2020-11-06
      • 2020-12-14
      • 2021-05-21
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 2019-08-13
      • 2021-01-10
      • 2020-12-02
      相关资源
      最近更新 更多