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

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

只是寻求一些关于这个带钩子的基本实现的帮助。我目前正在使用 Next.js 并希望在 _app.js 文件中设置一个上下文,以使其对整个组件树可用。

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

然后在index.js中添加组件loginForm.js,代码如下:

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>
)
}

现在在控制台中,我收到一条错误消息“未声明 dataContext”

这太简单了,我什至不知道如何解决这个问题,任何帮助将不胜感激。

React.createContext() 移到组件外:

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;

index.js 中的 dataContext 是什么?

 const info = React.useContext(dataContext)

我想你忘了导入上下文