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