【问题标题】:Current user with React Context具有 React 上下文的当前用户
【发布时间】:2020-11-11 12:41:50
【问题描述】:

我想有一种方法来使用 React Context 获取和获取当前用户(不将 props 传递给我的所有组件)

我尝试使用 React Context,但不明白如何从文档中获得像 const { currentUser, fetchCurrentUser } = useCurrentUser() 这样的东西。

【问题讨论】:

    标签: reactjs authentication react-context


    【解决方案1】:

    这是我为我的项目所做的:

    // src/CurrentUserContext.js
    import React from "react"
    
    export const CurrentUserContext = React.createContext()
    
    export const CurrentUserProvider = ({ children }) => {
      const [currentUser, setCurrentUser] = React.useState(null)
    
      const fetchCurrentUser = async () => {
        let response = await fetch("/api/users/current")
        response = await response.json()
        setCurrentUser(response)
      }
    
      return (
        <CurrentUserContext.Provider value={{ currentUser, fetchCurrentUser }}>
          {children}
        </CurrentUserContext.Provider>
      )
    }
    
    export const useCurrentUser = () => React.useContext(CurrentUserContext)
    

    然后像这样使用它:

    设置提供者:

    // ...
    import { CurrentUserProvider } from "./CurrentUserContext"
    // ...
    
    const App = () => (
      <CurrentUserProvider>
        ...
      </CurrentUserProvider>
    )
    
    export default App
    

    并在组件中使用上下文:

    ...
    import { useCurrentUser } from "./CurrentUserContext"
    
    const Header = () => {
      const { currentUser, fetchCurrentUser } = useCurrentUser()
    
      React.useEffect(() => fetchCurrentUser(), [])
    
      const logout = async (e) => {
        e.preventDefault()
    
        let response = await fetchWithCsrf("/api/session", { method: "DELETE" })
    
        fetchCurrentUser()
      }
      // ...
    }
    ...
    

    完整的源代码在 github 上:https://github.com/dorianmarie/emojeet

    该项目可以在以下位置进行现场试用:http://emojeet.com/

    如果useContext 返回undefined,那么您可能忘记了提供程序或需要将您的提供程序移到堆栈上。

    【讨论】:

      【解决方案2】:

      你没有解释你想对数据做什么,但是......在你执行函数获取后使用效果。 现在你的对象用户处于当前用户状态。 在使用 currentUser 后尝试控制台日志,看看里面有什么 dat。 在你可以将它与 currentUser 一起使用之后。“里面的任何道具”..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-22
        • 2018-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多