簡體   English   中英

如何保持用戶使用redux登錄?

[英]How can I keep a user logged in with redux?

我正在開發具有用戶身份驗證的應用程序。 現在,我的登錄當前在withAuth HOC中進行,而我的Nav組件已設置為獲取當前用戶。

但是,盡管用戶可以登錄並訪問其個人資料頁面,但是一旦他們離開個人資料,當前用戶將為空。

如何設置商店和/或組件,以便每個頁面上都有當前用戶。

我試圖將用戶傳遞給我的Nav組件,但是一旦您退出個人資料,就根本沒有用戶了

這是我的withAuth HOC:


export default function withAuth(WrappedComponent) {

  class Something extends React.Component {

    componentDidMount() { 

  **//checks if user is logged in before loading to the WrappedComponent (which in this case is the profile page)**

      if (!localStorage.token) {
        this.props.history.push("/login")
      }
      try {
        this.props.getCurrentUser()
        .catch(error => {
          this.props.history.push("/login")
        })
      } catch (error) {
        if (error.message === "Please log in") {
          this.props.history.push("/login")
        }
      }
      }

      render() {

        return (

<WrappedComponent />

      )}
    }

    const mapDispatchToProps = {
      getCurrentUser: getCurrentUserAction

**//does a fetch to 'http://localhost:3000/profile' with the bearer token and returns the username**

    }

    return withRouter(connect(null, mapDispatchToProps)(Something))
}

這是我的Nav組件(已導入到每個頁面):


  componentDidMount() {
    this.props.getCurrentUser();

**//This should fetch from 'http://localhost:3000/profile' with the bearer token and return the username**

  }
...
const mapStateToProps = state => {
  return {
    user: state.user
  };
};

const mapDispatchToProps = {
  getCurrentUser: getCurrentUserAction,
  logout: userLogoutAction
};

我了解為什么用戶在個人資料中不可見,但不理解為什么其他地方不可見

當安裝HoC組件時,它始終也會同時安裝Nav組件。

導航組件具有this.props.getCurrentUser(); this.props.setCurrentUser()相同。

我敢打賭,您有一些競賽條件,可以將用戶重定向回登錄。

我建議您重構代碼並正確使用redux,在這種情況下可能是

如果用戶已登錄,則getCurrentUserAction處理獲取用戶數據的請求,然后調度RECEIVE_USER操作,該操作更改redux狀態(通過reducer)。

HoC確保用戶已登錄並在必要時調度操作。

Nav組件使用選擇器來獲取所需的用戶數據(因為HoC在此處充當保護措施)。

以上可能不是您的最佳解決方案,但可以解決您的問題。

暫無
暫無

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

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