簡體   English   中英

Next.js-如何使用提供程序來包裝路由並使用帶有鈎子的上下文

[英]Next.js - How do I use Provider to Wrap Routes and use Context with Hooks

我在create-react-app中編寫了類似於以下代碼的代碼,我想知道next.js的等效代碼。 下面的代碼是我試圖讓所有頁面都可以使用的全局上下文。 提供者包裝鏈接。 我沒有錯誤。 問題是關於頁面的console.log(州)內,當我想到上下文狀態返回undefined。 我該如何解決?

謝謝。

頁/ 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;

頁/ 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;

頁/ 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}

您可以將<Provider>移到自定義的<App>組件中,該組件將初始化每個頁面。

頁/ _app.js

import React from 'react'
import App from 'next/app'
import {Provider} from './Context';

class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props
    return <Provider><Component {...pageProps} /></Provider>
  }
}

export default MyApp

更多信息在這里

這個想法是,您需要在樹中的任何位置都有一個父Provider以使用上下文。 就您而言,您的Provider不是About組件的父項。 您需要像這樣將您的Provider移動到_app.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM