我是react-redux
新手。在这里,我想做的是,当用户点击网址时,localhost:3000
用户应该直接移动到src/index.js localhost:3000/login页面。如果用户知道某些路由并在没有登录的情况下命中它们,那么它也应该将其重定向到 登录页面。
为此,我尝试过,
**Home.js**
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import App from './App';
import LoginComponent from './Components/loginComponent/LoginComponent';
class Home extends React.Component {
render() {
const rootPath = "/";
return (
<Switch>
<Route path={rootPath} component={App}/>
</Switch>
)
}
}
export default Home
**App.js**
import React from 'react';
import './App.css';
import { Provider } from 'react-redux';
import Main from './Containers/Main/Main';
import configureStore from './AppStore'
const store = configureStore()
class App extends React.Component {
render() {
return (
<Provider store={store}>
<div className="container-fluid">
<Main />
</div>
</Provider>
)
}
}
export default App
**Main.js**
import React from 'react';
import { Route, Redirect } from 'react-router';
import LoginComponent from '../../Components/loginComponent/LoginComponent';
import { LOGIN_REDIRECT_URL } from './../../Constants/AppConstants';
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
error: false,
hasUserLogedIn: false
}
}
render() {
const template =
!this.props.hasUserLogedIn
? (
<Route path="/*" render={(props) => <LoginComponent />}/>
) : (
<span>After login </span>
)
return (
<div>
{template}
</div>
)
}
}
function mapStateToProps(state) {
}
所以,在最后一个文件中,我正在执行该重定向,但它不起作用。 任何人都可以帮我吗? 由于/*
它将用户重定向到同一视图。
您可以使用公共和私有路由:
const PrivateRoute = ({ component: Component, ...rest, loggedIn }) => (
<Route
{...rest}
render={props =>
(loggedIn ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: LOGIN,
state: { from: props.location },
}}
/>
))
}
/>
);
const PublicRoute = ({ component: Component, ...rest, loggedIn}) => (
<Route
{...rest}
render={props =>
(!loggedIn ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: HOME,
state: { from: props.location },
}}
/>
))
}
/>
)