如果用户未登录,我试图重定向到登录页面。当我在App.js中使用路由时,工作正常,但是在创建单独的文件进行路由后,我却没有。
route.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;
App.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>
);
所以我希望这些路由正常工作。
答案 0 :(得分:1)
我制作了一个小沙箱来向您展示如何进行操作,我们将路由创建为一个函数,该函数从isLogin
开始进入App
状态,并根据该值呈现正确的组件。 / p>
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>
);
}
}