我在create-react-app中编写了类似于以下代码的代码,我想知道next.js的等效代码。下面的代码是我试图让所有页面都可以使用的全局上下文。提供者包装链接。我没有错误。问题出在 about 页面内,当我期望Context状态时,console.log(state)返回undefined。我该如何解决?
谢谢。
pages / index.js
import Link from "next/link";
import {Provider} from './Context';
function Index(){
return(
<div>
<Provider>
<ul>
<li><Link href="/"><a>Home</a></Link></li>
<li><Link href="/about"><a>About</a></Link></li>
</ul>
</Provider>
</div>
)
}
export default Index;
pages / about.js
import { useRouter } from 'next/router';
import {Context} from './Context';
import {useContext} from 'react';
const About= () => {
const data = useContext(Context);
console.log(data)
return (
<div>
<p>This is the blog post content.</p>
</div>
);
};
export default About;
pages / Context.js
import React, {createContext, useState, useEffect}from 'react';
let Context = createContext();
function Provider(props){
const initialState = {
userID: false,
user:undefined,
loading: true,
authenticated:false
}
const [state,updateState] = useState(initialState)
return(
<Context.Provider value={{
state:state
}}>
{props.children}
</Context.Provider>
)
}
const Consumer = Context.Consumer;
export {Provider, Consumer, Context}