我需要在history.push('/route')
的某个页面上重定向我的用户,但是如果我使用它,则更改网址
但该组件未呈现。
路由器:
// vanilla
import React from 'react';
// router
import {
BrowserRouter as Router,
Route,
Redirect
} from 'react-router-dom';
// component
import Login from '../controller/Login';
import history from '../history';
import Content from './Content';
import Categories from './Categories';
import Author from './Author';
import NavbarView from '../view/Navbar.view';
function PrivateRoute({children, ...rest}: any) {
const jwtExist = !!localStorage.getItem('jwt');
return (
<Route
{...rest}
render={ ({location}) =>
jwtExist ?
(children) :
(<Redirect to={{pathname: '/login', state: {from: location}}}/>)
}
/>
)
}
class App extends React.Component {
render() {
return (
<Router>
<Route path='/login' component={Login}/>
<PrivateRoute path='/admin'>
<NavbarView/>
<Route path={'/admin/contents'} component={Content} />
<Route path={'/admin/categories'} component={Categories} />
<Route path={'/admin/authors'} component={Author} />
</PrivateRoute>
</Router>
)
}
}
export default App;
和“重定向”:
import history from '../history';
const checkJwt: () => any = () => {
fetch('http://localhost:3001/auth/validate', {
headers: {
'Authorization' : `Bearer ${localStorage.getItem('jwt')}`
}
})
.then((res: any) => {
console.log(res);
if (res.status !== 200) {
history.push('/login')
}
})
};
export default checkJwt;
如果我尝试将history
放在路由器中,如下所示:
<Router history={history}>
我收到以下错误:
No overload matches this call.
Overload 1 of 2, '(props: Readonly<BrowserRouterProps>): BrowserRouter', gave the following error.
Type '{ children: Element[]; history: History<any>; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<BrowserRouter> & Readonly<BrowserRouterProps> & Readonly<{ children?: ReactNode; }>'.
Property 'history' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<BrowserRouter> & Readonly<BrowserRouterProps> & Readonly<{ children?: ReactNode; }>'.
Overload 2 of 2, '(props: BrowserRouterProps, context?: any): BrowserRouter', gave the following error.
Type '{ children: Element[]; history: History<any>; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<BrowserRouter> & Readonly<BrowserRouterProps> & Readonly<{ children?: ReactNode; }>'.
Property 'history' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<BrowserRouter> & Readonly<BrowserRouterProps> & Readonly<{ children?: ReactNode; }>'. TS2769
33 | render() {
34 | return (
> 35 | <Router history={history}>
| ^
36 | <Route path='/login' component={Login}/>
37 | <PrivateRoute path='/admin'>
38 | <NavbarView/>
我的历史记录文件如下:
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
答案 0 :(得分:0)
只需使用"react-router-dom"
上的路由器
替换
import {
BrowserRouter as Router,
Route,
Redirect
} from 'react-router-dom';
使用
import {
Router,
Route,
Redirect
} from 'react-router-dom';
,因为BrowserRouter不接受历史记录支持。 这对我有用。