简体   繁体   English

反应上下文正在给出未定义的对象

[英]react context is giving undefined object

In my react application I am trying to use context api.在我的反应应用程序中,我试图使用上下文 api。 In my component I am importing the context but it is giving error that object can not destructure the property.在我的组件中,我正在导入上下文,但它给出了对象无法解构属性的错误。 I am trying to implement cart functionality in my app.我正在尝试在我的应用中实现购物车功能。 I am using hooks.我正在使用钩子。

ImgContext.js图像上下文.js

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

const ImgContext = createContext();

const ImgConProvider = ({children}) => {
    const [myCart, setMyCart] = useState([]);

    return(
    <ImgContext.Provider value={{myCart, setMyCart}}>
        {children}
    </ImgContext.Provider>
    )
}

export {ImgContext, ImgConProvider}

ImageGrid.js图像网格.js

import React, { useContext, useState } from 'react';
import ImageGrid from './ImageGrid';
import { ImgContext } from './Context/ImageContext';

const Home = () => {

    const { myCart } = useContext(ImgContext);

    return (
    <div className="App">
      {myCart}
    </div>
    )
}

export default  Home;

You are not providing aa default value when creating the context.创建上下文时,您没有提供默认值。 If there is a scenario where the component doenst have access to a provider the value from context would be undefined which maybe causing the issue.如果存在组件确实有权访问提供程序的情况,则上下文中的值将是未定义的,这可能会导致问题。 Better provide a default value.最好提供一个默认值。

const ImgContext = createContext({});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM