我有一个呈现路线本身的组件。我想使用RouteComponentProps访问location属性,但是在将组件更改为以下方式时出现一些类型错误:
Microsoft.Net.Compilers.Toolset
Routes.tsx
import { render } from 'react-dom';
import { Redirect, Route, Switch } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import React from 'react';
import RouteParams from './Routes';
import { map } from 'lodash';
const App = () => {
<BrowserRouter>
<Switch>
{map(RouteParams().routes, route => {
return (
<Route exact path={route.pathName} component={route.component} />
);
})}
<Redirect to="/a" />
</Switch>
</BrowserRouter>
}
render(<App />, document.getElementById('root'));
我在导入组件时以及在组件中都出现错误。请指教。任何帮助表示赞赏。
错误是:
答案 0 :(得分:0)
RouteParams
,它被导入并用作App.tsx
中的对象,如下所示:{map(RouteParams().routes, route => {
return (
<Route exact path={route.pathName} component={route.component} />
);
})}
RouteParams
被定义为功能组件BUT,它不返回任何JSX(组件应返回JSX)。因此,从技术上讲,它不会充当组件。RouteParams
转换为一个钩子。为此,我删除了高阶组件withRouter
(因为它现在是一个挂钩)。还使用常规的钩子名称useRouteParams
对其进行命名(这不是必需的)。import React from "react";
import { useLocation } from "react-router-dom";
import { RouteComponentProps } from "react-router";
const A = () => <p>A</p>;
const B = () => <p>B</p>;
const C = () => <p>C</p>;
interface IRouteParams {
pathName: string;
search: string[];
label: string;
component:
| React.ComponentType<RouteComponentProps<any>>
| React.ComponentType<any>;
}
const useRouteParams = () => {
const showForAdmin = true;
const location = useLocation();
const { search } = location;
console.log(search);
const scenarioManagerRoute: IRouteParams = {
pathName: "/a",
search: ["a"],
label: "a",
component: A
};
const routes: IRouteParams[] = [
scenarioManagerRoute,
{
pathName: "/b",
search: ["b"],
label: "B",
component: B
}
];
if (showForAdmin) {
routes.push({
pathName: "/c",
search: ["c"],
label: "C",
component: C
});
}
return { routes, scenarioManagerRoute };
};
export default useRouteParams;
您可能会看到,我使用了useLocation()
的{{1}}钩子来使用react-router-dom
。休息都一样。
location
中,我们将需要进行一些小的调整。App.tsx