【问题标题】:React Router - Preserve current route after page refreshReact Router - 页面刷新后保留当前路由
【发布时间】:2018-04-04 02:47:03
【问题描述】:

我是 SPA 开发的新手。我使用 React 和 React Router 并制作了简单的应用程序。它有两个页面:公共页面和受保护页面。用户只有在登录后才能看到受保护的页面。我使用 firebase 来管理用户。

问题是当我进入受保护的页面,登录并可以看到它的内容时,我重新刷新页面并重定向到“默认”状态,即公共页面。

index.js

ReactDOM.render(<App />, document.getElementById('root'));

App.js

const ProtectedPage = () => {
  return (
    <div>
      <h1> Protected page. </h1>
      <Link to="/">Public resources</Link>
    </div>
  );
}

const PublicPage = () => {
  return (
    <div>
      <h1> Public page. </h1>
      <p> Login to see protected resources </p>
      <Link to="/protected">Protected resources</Link>
    </div>
  );
}

const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
  <Route {...rest} render={props => (
    isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

class App extends React.Component {
  constructor(props) {
    super(props);

    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);

    this.state = {
      username: '',
      uuid: ''
    }
  }

  login() {
    auth.signInWithEmailAndPassword(email, password).then((user) => {
      console.log('Sign in ', user.displayName);
      this.setState({
        username: user.displayName,
        uuid: user.uuid
      });
    });
  }

  logout() {
    auth.signOut().then(() => {
      console.log('Sign out ');
      this.setState({
        username: '',
        uuid: '' 
      });
    })
  }

  componentDidMount() {
    this.releaseFirebaseAuthHandler = auth.onAuthStateChanged((user) => {
      if(user) {
        this.setState({
          username: user.displayName,
          uuid: user.uuid
        });
      }
    });
  }

  componentWillUnmount() {
    this.releaseFirebaseAuthHandler();
  }

  render() {
    return (
      <div>
        <div className="navbar">
          <nav className="navbar-nav">
            { this.state.username ? 
              <button onClick={this.logout}>Logout</button> :
              <button onClick={this.login}>Login</button> }
          </nav>
        </div>
        <div>
            <div>
              <Route exact path="/" component={PublicPage} />
              <PrivateRoute path="/protected" component={ProtectedPage} isAuthenticated={this.state.uuid !== ''} />
            </div>
        </div>
      </div>
    ); 
  }
}

export default App;

是否可以在不涉及服务器的情况下刷新 localhost:3000/protected 页面?

【问题讨论】:

  • 这里真正的问题是如何在刷新后保持用户身份验证,不是吗?您可以将 uuid 存储在 localStorage 中。然后在应用构造函数中:this.state = { uuid: localStorage.getItem('uuid') || ''}

标签: reactjs react-router


【解决方案1】:

如果用户未通过身份验证,则在您的代码中重定向到 pathname: '/'

const PrivateRoute = (...) => (
  <Route {...rest} render={props => (
   isAuthenticated 
     ? <Component {...props}/>
     : <Redirect to={{
        pathname: '/',
        state: { from: props.location }
       }}/>
   )}/>
 )

如果您想在 url 中保留 /protected,一种方法是将重定向替换为 &lt;div&gt;Please login&lt;/div&gt; 之类的内容

【讨论】:

    【解决方案2】:

    状态不会跨多个会话保留,为此您可以使用localStorage

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-28
      • 2018-05-16
      • 2017-12-10
      • 1970-01-01
      • 2011-08-23
      • 2015-11-28
      • 1970-01-01
      • 2017-03-05
      相关资源
      最近更新 更多