requireAuth with react-router v4和redux

时间:2017-10-19 16:25:43

标签: javascript reactjs redux react-router react-router-v4

我有检查的HOC是登录用户。

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

1 个答案:

答案 0 :(得分: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} />;
    }
  };
}