所以我在Gatsby应用程序中使用React的上下文API(基本上是用React写的)来处理用户身份验证。我有两个使用该上下文的组件:dashboard
和navBar
。当我尝试登录和注销时,我的navBar
会根据我的userContext
的行为而有所不同,但是我的dashboard
不会响应。它与结构有关吗,例如navBar
是layout
的直接“孩子”,而dashboard
不是?毕竟我不认为这就是为什么我使用contextAPI
然后仅仅通过一个正常的道具。
以下是代码:
//layout.js
import React, { useContext, useState, createContext } from "react"
import Navbar from "../components/navBar"
import {monitorAuth} from "../firebase/firebaseService"
export const UserStateContext = createContext(null)
export const SetUserContext = createContext()
const Layout = ({ children }) => {
const [user, setUser] = useState()
console.log(user)
monitorAuth(setUser)// everytime a layout component renders, it will grab a user if it is logged inthen setUser, then I will use it in the context
return (
<>
<UserStateContext.Provider value={user}>
<SetUserContext.Provider value={setUser}>
<div>
<SEO />
<Navbar />
<main>{children}</main>
</div>
</SetUserContext.Provider >
</UserStateContext.Provider>
</>
)
}
export default Layout
import React, { useState, useContext } from "react"
import AppBar from "@material-ui/core/AppBar"
import { signOut } from "../firebase/firebaseService"
import {UserStateContext} from "./layout"
export default function NavBar() {
const user = useContext(UserStateContext)
console.log(user) // when I log in/ log out, it will console.log the right user status, user/null
const renderMenu = () => {
return (
<>
{user? (
<>
<Button onClick={signOut}>Sign Out</Button>
<Button>My profile</Button>
</>)
:<Button>Sign In</Button> }
</>
)
}
return (
<AppBar position="static" className={classes.root}>
...
{renderMenu()}
...
</AppBar>
)
}
//dashboard.js
import React, { useContext } from 'react'
import Layout from '../components/layout'
import LoggedIn from '../components/dashboard/loggedIn'
import NotLoggedIn from '../components/dashboard/notLoggedIn'
import {UserStateContext} from "../components/layout"
const Dashboard = props => {
console.log("within dashboard")
const user = useContext(UserStateContext)
console.log(user)
const renderDashboard = () =>{
return (
<>
{user? <LoggedIn /> : <NotLoggedIn />}
</>
)
}
return(
<Layout>
{renderDashboard()}
</Layout>
)
}
export default Dashboard
还有一个线索,我在所有三个组件中都用console.log user
刷新页面时:
within dashboard
dashboard.js:17 null
layout.js:15 undefined
navBar.jsx:54 undefined
layout.js:15 [user...]
navBar.jsx:54 [user...]
layout.js:15 [user...]
这意味着,起初尚未设置user
,因此所有三个组件都将user
记录为undefined
,但后来,layout
检测到{{1 }},然后对其进行更新,因此user
也知道,但navbar
不知道。与dashboard
有关吗?谢谢!
答案 0 :(得分:1)
它不起作用的原因是因为您的<Dashboard>
组件不是上下文提供程序的子级。如果您使用React devtools,您会看到组件树看起来像
<Dashboard>
<Layout>
<UserStateContext.Provider>
<SetUserContext.Provider>
...
</SetUserContext.Provider>
</UserStateContext.Provider>
</Layout>
</Dashboard>
当上下文值更改时,它将在其子树中寻找useContext
的组件。但是,Dashboard
不是孩子,而是父母!
如果要遵循这种模式,一个解决方案可能是创建Dashboard
的父组件并将上下文放在那里。