【发布时间】:2020-03-19 04:32:41
【问题描述】:
我有一个路由器可以传递位置和子节点的道具,但我不知道这些道具的正确类型是什么。
这是使用 react-router-dom 的路由器...
import React, { useReducer } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { globalContext, setGlobalContext } from './components/context';
import { Layout } from './components/layout';
import { defaultState, globalReducer } from './components/reducer';
import { Home } from './routes/home';
import { NotFound } from './routes/notFound';
const Router: React.FC = () => {
const [global, setGlobal] = useReducer(globalReducer, defaultState);
return (
<setGlobalContext.Provider value={{ setGlobal }}>
<globalContext.Provider value={{ global }}>
<BrowserRouter>
<Route
render={({ location }) => (
<Layout location={location}>
<Switch location={location}>
<Route exact path='/' component={Home} />
<Route component={NotFound} />
</Switch>
</Layout>
)}
/>
</BrowserRouter>
</globalContext.Provider>
</setGlobalContext.Provider>
);
};
export { Router };
在布局组件内部,我有一个用于位置和子项的接口,但是因为我不知道这些的正确类型,我最终使用了任何类型,然后我的 linter 就会出现问题。
import React from 'react';
interface PropsInterface {
children: any;
location: any;
}
const Layout: React.FC<PropsInterface> = (props: PropsInterface) => {
return (
<div>
<p>{props.location}</p>
<p>{props.children}</p>
</div>
);
};
export { Layout };
我得到的错误是“any”的类型声明失去了类型安全性。考虑用更精确的类型替换它。 (no-any)tslint(1)
我可以从导入import { useLocation } from 'react-router-dom';获取位置
【问题讨论】:
标签: reactjs typescript react-router-v4