简体   繁体   中英

Not declared context error using context hook in react with next.js

just asking for some help with this basic implementation with hooks. I am currently working with Next.js and want to set a context in the _app.js file in order to make it available to the entire component tree.

import React from "react";

function MyApp({ Component, pageProps }) {
  const dataContext = React.createContext()
  return (
    <dataContext.Provider value = 'just some text'>
      <Component {...pageProps} />
    </dataContext.Provider>
  )
}
export default MyApp

Then in the index.js, add the component loginForm.js with the following code:

import React from "react";

function LoginForm (props) {

  const info = React.useContext(dataContext)
  const onSubmit = () => console.log(info)

return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <button type="submit">click here</button>
   </form>
)
}

now in the console, I receive an error that says "dataContext is not declared"

显然上下文存在

  • Apparently, the context exists -

This is so simple that I don't even know how to tackle the issue, any help would be greatly appreciated.

Move React.createContext() outside the component:

import React from "react";

const DataContext = React.createContext();

function MyApp({ Component, pageProps }) {
  return (
    <DataContext .Provider value="just some text">
      <Component { ...pageProps } />
    </DataContext.Provider>
  );
}

export default MyApp;

What is dataContext in index.js?

 const info = React.useContext(dataContext)

I think you forgot to import the context

let d = useMyContextHook() const draw = d? d.draw: null

This fixed it for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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