考虑以下React Router V4代码:
const isAuthenticated = () => {
let hasToken = localStorage.getItem("jwtToken");
if (hasToken) return true;
return false;
};
const AuthenticatedRoute = ({ component: Component, ...rest }) =>
<Route
{...rest}
render={props =>
isAuthenticated()
? <Component {...props} />
: window.location = "/auth/login" } <<-- ERROR HERE
/>;
class App extends Component {
render() {
return (
<BrowserRouter basename="/editor">
<Switch>
<AuthenticatedRoute exact path="/" component={AppHome} />
<AuthenticatedRoute
exact
path="/:module"
component={AppNav}
/>
<Route component={PageNotFound} />
</Switch>
</BrowserRouter>
);
}
}
export default App;
auth/login
是需要从服务器加载的另一个ReactJs应用程序,换句话说,auth/login
需要绕过客户端路由并发送到服务器,在那里它将被路由并将服务于新的ReactJS应用程序(auth
应用程序与login
页面)。
尝试重定向(未经过身份验证)时,我在浏览器控制台上收到以下错误:
You are attempting to use a basename on a page whose URL path does not begin with a basename.
Expected path "/login" to begin with "/editor"
看起来我被“困在”React Router V4中,没有任何东西可以脱离基本名称。
如何解决这个问题并重定向到服务器页面,退出或绕过反应路由器本身?
答案 0 :(得分:0)
您需要在应用中安装react-router-dom
yarn add react-router-dom
或
npm i -S react-router-dom
并导入此
import { BrowserRouter as Router } from 'react-router-dom';
您要重定向的位置
browserHistory.push('/path/some/where');
您的代码应
import { BrowserRouter as Router } from 'react-router-dom';
const isAuthenticated = () => {
let hasToken = localStorage.getItem("jwtToken");
if (hasToken) return true;
return false;
};
const AuthenticatedRoute = ({ component: Component, ...rest, history }) =>
<Route
{...rest}
render={props =>
isAuthenticated()
? <Component {...props} />
: history.push("/auth/login")}
/>;
class App extends Component {
render() {
return (
<BrowserRouter basename="/editor">
<Switch>
<AuthenticatedRoute exact path="/" component={AppHome} />
<AuthenticatedRoute
exact
path="/:module"
component={AppNav}
/>
<Route component={PageNotFound} />
</Switch>
</BrowserRouter>
);
}
}
export default App;
答案 1 :(得分:0)
您应该使用Redirect
react-router-dom
组件
import { Redirect, Route } from 'react-router-dom';
const AuthenticatedRoute = ({ component: Component, ...rest }) =>
<Route
{...rest}
render={props =>
isAuthenticated()? <Component {...props} />
: (
<Redirect
to={{ pathname: 'auth/login' }}
/>
)
}
/>
这是一个有效的example