我正在尝试创建一个PrivateRoute
,它将包装Route
中的react-router-dom
组件。在此组件中,我要检查用户是否具有令牌,并基于该令牌拒绝或授予对他们尝试导航到的屏幕的访问权限。问题是我很难用打字稿输入该组件的道具。
这是代码。
import * as React from "react";
import { Route, RouteProps } from "react-router-dom";
const ProtectedRoute = (props: RouteProps) => {
return (
<Route
path={props.path}
exact={props.exact}
render={renderProps => {
const token = localStorage.getItem("myToken");
if (token) {
const Component = props.component;
return (
<Component {...renderProps} />
)
}
}}
/>
);
};
export default ProtectedRoute;
这是我使用的地方。
import * as React from 'react';
import { ThemeProvider } from "styled-components";
import { Switch, Route, BrowserRouter } from "react-router-dom";
import Loadable from "react-loadable";
import Loader from "components/Loader";
import ProtectedRoute from "components/PrivateRoute";
const Login = Loadable({
loader: () => import("routes/Login"),
loading: Loader,
})
const Home = Loadable({
loader: () => import("routes/home"),
loading: Loader,
})
const App: React.FC = () => {
const theme = {
};
return (
<ThemeProvider theme={theme}>
<BrowserRouter>
<Switch>
<Route path="/login" component={Login} />
<ProtectedRoute path="/" exact component={Home} />
</Switch>
</BrowserRouter>
</ThemeProvider>
);
}
export default App;
麻烦的是,当我尝试使用Route
组件的渲染道具来渲染传入的组件时,出现以下错误。
JSX元素类型“ Component”没有任何构造或调用 签名
有什么想法吗?
答案 0 :(得分:0)
我不确定它是否会涵盖您的全部用例,但您可以看看
我刚刚对您的ProtectedRoute
import React from "react";
import { Route } from "react-router-dom";
const ProtectedRoute = props => {
return (
<Route
path={props.path}
exact={props.exact}
Component={renderProps => {
const token = localStorage.getItem("myToken");
if (token) {
const Component = props.component;
return <Component {...renderProps} />;
}
}}
/>
);
};
export default ProtectedRoute;
对于反应中的道具类型检查,您可以使用prop-types