My useContext hook is not working, am unable to find error

huangapple go评论57阅读模式
英文:

My useContext hook is not working, am unable to find error

问题

以下是您要翻译的部分:

这是我的Next.js项目。
我已经单独创建了 useContext 文件夹,在那里我写了我想要在我的每个文件或组件中使用的对象或数据,并且为了这样做,我将我的 _app.js 文件包装在 context 中,但是当我在我的一个页面中使用它时,它显示未定义的错误。无法理解。
下面我发送了我的每一部分文件。

useContext/useContexthere.js

```jsx
import React, { createContext, useContext } from 'react';

const UserContext = createContext();

const UseContexthere = ({ children }) => {
    const biodata = {
        name: "Manish",
        profession: "Coder & Rapper",
        age: 25
    }
    return (
        <>
            <UserContext.Provider value={{ biodata }}>
                {children}
            </UserContext.Provider>
        </>
    )
}

export default UseContexthere;

_app.js -- 在 Next.js 中

import '@/styles/globals.css';
import UseContexthere from './useContext/useContexthere';

export default function App({ Component, pageProps }) {
    return (
        <UseContexthere>
            <Component {...pageProps} />
        </UseContexthere>
    )
}

about.js -- 在这里使用我的上下文内容

import React, { useContext } from 'react';
import UseContexthere from './useContext/useContexthere';

const About = () => {
    const user = useContext(UserContext);
    return (
        <div>
            <div>
                <h3>以下数据通过 useContext Hook 传递</h3>
                <p>我的名字是 {user.name}</p>
            </div>
        </div>
    )
}

export default About

但是它显示未定义的错误。我做错了什么?


请注意,我已经将代码中的 HTML 标签和格式保留为原始输入中的格式。如果需要进一步的帮助,请告诉我。

<details>
<summary>英文:</summary>

It is my next.js project  
I have separately made the useContext  folder and there I wrote my object or data which  I want to use by my every files or components , and to do so I enclosed my \_app.js file with the context one, but when I am using it in my one of the page, it showing undefined error. Unable to understand  
Below am sending my every bit of fies


useContext/useContextherehere.js

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

const UserContext = createContext();

const UseContexthere = ({children}) => {
const biodata = {
name : "Manish",
profession : "Coder & Rapper",
age : 25
}
return (
<>
<UserContext.Provider value={{biodata}}>
{children}
</UserContext.Provider>
</>
)
}

export default UseContexthere;


_app.js -- in next.js

import '@/styles/globals.css';
import UseContexthere from './useContext/useContexthere';

export default function App({ Component, pageProps }) {
return (
<UseContexthere>
<Component {...pageProps} />
</UseContexthere>
)

}


about.js -- using here my context thing

import React, {useContext} from 'react';
import UseContexthere from './useContext/useContexthere';

const About = () => {
const user = useContext(UseContexthere);
return (
<div>
<div>
<h3>Following data is coming through useContext Hook</h3>
<p>Hey my name is {user.name}</p>

    &lt;/div&gt;
&lt;/div&gt;

)
}

export default About


but than it showing me error of undefined. What am I doing wrong?

</details>


# 答案1
**得分**: 2

## Edit:
这里有一个关于此答案详细信息的 NextJS stackblitz:

https://stackblitz.com/edit/stackblitz-starters-esbbm1?file=pages%2Findex.js

## Answer:

这是因为您没有使用正确的导入方式。

您需要导出实际的上下文(不仅仅是提供者组件):

```javascript
export const UserContext = createContext();

并且在您的消费组件中,您需要使用该导出,而不是默认导出:

import { UserContext } from './useContext/useContexthere';

...

const user = useContext(UserContext);

在实际应用中,React 应用通常还会从创建上下文的地方导出这个钩子,以使事情变得更简单:

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

const UserContext = createContext();

// 现在只需在您的组件中导入此钩子
export const useUserContext = () => React.useContext(UserContext)

...

这是除了其他答案中提到的拼写错误之外的额外信息。

英文:

Edit:

Here's a NextJS stackblitz of the details of this answer:

https://stackblitz.com/edit/stackblitz-starters-esbbm1?file=pages%2Findex.js

Answer:

It's because you're not using the correct import

You need to export the actual context (not just your provider component):

export const UserContext = createContext();

and in your consuming component you need to use that export, not the default export:

import { UserContext } from &#39;./useContext/useContexthere&#39;;


...

    const user = useContext(UserContext);

In practice, what is common in React applications is the hook is also exported from the place the context is created, just to keep things simpler:

import React, { createContext, useContext} from &#39;react&#39;;

const UserContext = createContext();

// now just import this hook in your component
export const useUserContext = () =&gt; React.useContext(UserContext)

...

This is in addition to the typos details by the other answers

答案2

得分: 0

<UserContext.Provider value={{ biodata }}>
<p>我的名字是 {user.name}</p>

你正在创建一个带有 biodata 属性的对象,但随后尝试访问一个名为 name 的属性。要修复这个问题,可以将提供的值更改为只包含 biodata 对象,而不是嵌套在另一个对象中:

<UserContext.Provider value={biodata}>

或者更改使用上下文的方式以期望 biodata 属性:

<p>我的名字是 {user.biodata.name}</p>
英文:
&lt;UserContext.Provider value={{biodata}}&gt;
&lt;p&gt;Hey my name is {user.name}&lt;/p&gt;

You are creating an object with a biodata property, but then you are trying to access a name property. To fix this, either change the provided value to be just the biodata object, not nested inside another object:

&lt;UserContext.Provider value={biodata}&gt;

Or change the way you consume the context to expect the biodata property:

&lt;p&gt;Hey my name is {user.biodata.name}&lt;/p&gt;

答案3

得分: 0

这是由于双花括号而实际发生的情况。

const biodata = {
  name: "Manish",
  profession: "Coder & Rapper",
  age: 25
}

let x = { biodata };

console.log(x);

您没有传递biodata,而是一个具有biodata作为键的对象。
只需更新您的代码如下:

<UserContext.Provider value={biodata}>
  {children}
</UserContext.Provider>
英文:

This is what is essentially happening because of double curly braces.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const biodata = {
        name : &quot;Manish&quot;,
        profession : &quot;Coder &amp; Rapper&quot;,
        age : 25
    }

let x = {biodata};

console.log(x);

<!-- end snippet -->

You are not passing biodata, but an object which has biodata as a key.
Just update your code like:

&lt;UserContext.Provider value={biodata}&gt;
          {children}
      &lt;/UserContext.Provider&gt;

huangapple
  • 本文由 发表于 2023年6月29日 19:46:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580731.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定