2017-10-19 118 views
0

我有HOC檢查是登錄用戶。requireAuth與react-router v4和redux

import React from 'react'; 
import { Redirect } from 'react-router-dom'; 

export default function requireAuthComponent(store, Component, redirectTo = '/') { 
    return class RequireAuthComponent extends React.Component { 
    render() { 
     const state = store.getState(); 
     const auth = state.auth; 

     if (auth.logged) { 
     return <Component {...this.props} />; 
     } 

     return <Redirect to={redirectTo} />; 
    } 
    }; 
} 

和路由

import PrivatContainer from './container/PrivatContainer'; 
import requireAuth from '../../components/requireAuth'; 

export default store => ({ 
    path: '/privat', 
    exact: true, 
    component: requireAuth(store, PrivatContainer), 
}); 

PrivatComponent

import React from 'react'; 

export default ({ auth: { logged }, toggleLogin }) => (
    <div> 
    <h1>Privat Route</h1> 
    <h3>User is {logged.toString()}</h3> 
    <button onClick={() => toggleLogin()}>Logout</button> 
    </div> 
); 

當路由所有工作正常,但是當我改變存儲與logged: false,我還是留在此組件上先輸入(線路)因爲路由調用一次,而不更新商店更新,它如何修正或訂閱RequireAuthComponent對商店更新?

+0

我詳細介紹瞭如何在[驗證HOC]解釋(https://stackoverflow.com/questions/46379934/ react-router-v4-authorized-routes-with-hoc)可以被寫入。如果您發現我的答案有用,請讓我知道。 –

回答

0

也許這是不正常的,所以如果你有更好的想法,請告訴我:)

export default function requireAuthComponent(store, Component, redirectTo = '/') { 
    return class RequireAuthComponent extends React.Component { 
    state = { 
     listener: null, 
    } 

    componentWillMount() { 
     const listener = store.subscribe(() => { 
     this.forceUpdate(); 
     }); 

     this.setState({ listener }); 
    } 

    componentWillUnmount() { 
     const { listener } = this.state; 

     listener(); 
     this.setState({ listener: null }); 
    } 

    render() { 
     const state = store.getState(); 
     const auth = state.auth; 

     if (auth.logged) { 
     return <Component {...this.props} />; 
     } 

     return <Redirect to={redirectTo} />; 
    } 
    }; 
} 
+0

您可以使用「連接」功能將您的HOC組件連接到Redux。這樣您就不需要手動訂閱和取消訂閱,並且您的組件將在狀態更改時進行更改。如果您仍然需要示例,我可以將其作爲答案發布。 –