0

如果用户未登录,我试图重定向到登录页面。当我在 App.js 中使用路由时它工作正常,但在为路由制作单独的文件后我没有。

路由.js

import React from 'react';
import Login from './Login';
import Register from './Register';
import Home from './Home';
import './style.css';
import { Route, Switch } from 'react-router-dom';

const routes = (
        <Switch>
            <Route key="0" path="/" exact render={ props => <Home {...props} />} />
            <Route key="1" path="/login" render={ props => <Login {...props} />} />
            <Route key="2" path="/register" render={ props => <Register {...props} />}  />
            <Route key="2" path="/home"  render={ props => <Home {...props} /> } />
        </Switch>
        );

export default routes;

应用程序.js

class App extends Component {
  state={
    isLogin:false
  }
  render() {
    return (

      <div className="App">
      <Router>
      <Header/>
    <div className="container">
      {routes}

    </div>
    </Router>

      </div>
    );
  }
}

我之前的溃败条件是

const routes = (
           <Switch>
            <Route key="0" path="/" exact render={ () => this.state.login ? ( <Home/> ): ( <Redirect to="/login"/> )} />} />
            <Route key="1" path="/login" render={ props => <Login {...props} />} />
            <Route key="2" path="/register" render={ props => <Register {...props} />}  />
            <Route key="2" path="/home"  render={ () => this.state.login ? ( <Home/> ): ( <Redirect to="/login"/> )} />
          </Switch>
        );

所以我希望这些路线能够正常工作。

4

1 回答 1

1

我制作了一个小沙箱来向您展示如何做到这一点,我们将路由创建为一个函数,该函数从我们呈现正确组件的值中获取isLogin状态App并基于该值。

const Home = () => <h1>Home</h1>;
const Login = () => <h1>Login</h1>;
const Register = () => <h1>Register</h1>;

const Nav = () => (
  <div>
    <Link to="/">Home</Link>
    <Link to="/login">Login</Link>
    <Link to="/register">Register</Link>
  </div>
);
// Takes isLogged from this.state
const routes = isLogged => (
  <Switch>
    <Route
      path="/"
      exact
      render={() => (isLogged ? <Home /> : <Redirect to="/login" />)}
    />
    } />
    <Route path="/login" render={props => <Login {...props} />} />
    <Route path="/register" render={props => <Register {...props} />} />
    <Route
      path="/home"
      render={() => (isLogged ? <Home /> : <Redirect to="/login" />)}
    />
  </Switch>
);

class App extends Component {
  state = {
    isLogin: false
  };

  toggleLogin = () =>
    this.setState(prevState => ({
      isLogin: !prevState.isLogin
    }));

  render() {
    const { isLogin } = this.state;

    return (
      <Router>
        <div className="App">
          <button onClick={this.toggleLogin}>Toggle Login</button>
          <Nav />
          <h1>{`isLogin ${isLogin}`}</h1>
          {/* invoke routes with isLogin */}
          {routes(isLogin)}
        </div>
      </Router>
    );
  }
}

沙盒

于 2019-04-09T09:33:20.063 回答