React JS上下文返回未定义

时间:2020-04-05 09:35:57

标签: reactjs react-context

我想将一些数据传递给我的所有React组件,因为我创建了一个名为GlobalContex的上下文,该上下文包装了所有组件。现在,此GlobalContex将数据从prop提取到其MainComponent中。

当我在GlobalContext中console.log这个数据时,我可以在浏览器的控制台中看到该数据,但是当我在GlobalContext子组件和控制台之一中使用此数据时,它返回未定义的内容。 / p>

这是我的代码

MainComponent.js

import React from 'react';
import Header from "./Header";
import Sidebar from "./Sidebar";

import {
    Route,
    BrowserRouter
} from "react-router-dom";
import UserIndex from "../user/UserIndex";
import TrackerIndex from "../tracker/TrackerIndex";
import AuthUserContextProvider from '../../contexts/AuthUserContext';
import GlobalContextProvider from "../../contexts/GlobalContext";

const MainComponent = (props) => {

    const global_data = JSON.parse(props.testProp);

    return (
        <BrowserRouter>
            <div id="wrapper" className="menu-displayed">

                <GlobalContextProvider global_data={global_data}>

                    <div className="prd-container">

                        <Header/>

                        <div className="content">
                            <Route path="/users" component={UserIndex}/>
                            <Route path="/tracker" component={TrackerIndex}/>
                        </div>

                    </div>

                    <Sidebar/>

                </GlobalContextProvider>

            </div>
        </BrowserRouter>
    );

};

export default MainComponent

GlobalContext.js

import React, {createContext, useState, useEffect} from 'react'

export const GlobalContext = createContext();

const GlobalContextProvider = (props) => {

    const [context_global_data, setGlobalData] = useState([]);

    useEffect(() => {
        setGlobalData(props.global_data)
    },[])


    console.log(context_global_data);
    return (
        <GlobalContext.Provider value={{context_global_data}}>
            {props.children}
        </GlobalContext.Provider>
    )
}

export default GlobalContextProvider

从全局上下文控制台

{auth_user: {…}, login_url: "http://127.0.0.1:8000/login", logout_url: "http://127.0.0.1:8000/logout"}
auth_user: {id: 1, name: "Dust Value", email: "dustvalue@dustvalue.com", profile_pic: "dummy.jpg", email_verified_at: null, …}
login_url: "http://127.0.0.1:8000/login"
logout_url: "http://127.0.0.1:8000/logout"

Sidebar.js

import React, {useContext, useState, useEffect} from 'react';
import {NavLink, Link} from 'react-router-dom';
import GlobalContext from "../../contexts/GlobalContext";


const Sidebar = (props) => {

    const global_data = useContext(GlobalContext);

    useEffect(() => {
        console.log(global_data);
    })


    return (
        <div>
             Sidebar
        </div>
    )
export default Sidebar

0 个答案:

没有答案