【问题标题】:React Use RouteComponentProps - Type '{}' is missing the following properties from type 'Readonly<RouteComponentProps<{}React 使用 RouteComponentProps - 类型“{}”缺少“Readonly<RouteComponentProps<{} 类型的以下属性
【发布时间】:2019-09-23 21:58:08
【问题描述】:

我正在使用带有 Typescript 的 React,并且需要使用历史记录,因为我需要有 RouteComponentProps 接口

export default class Routes extends Component<RouteComponentProps, any> {
  render() {
   return (
    <div>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/login" component={Login} />
        <ProtectedRoute exact path="/admin" component={Admin} />
      </Switch>
    </div>
  );
 }}

当我将 props 接口用作 RouteComponentProps 时,下面的代码会出现错误。

class App extends Component {
  render() {
   return (
     <Provider>
       <React.Fragment>
         <Navbar />
         <Routes />
       </React.Fragment>
     </Provider>
 );
}
}

当我尝试使用我的路由组件时出现错误。错误说

类型“{}”缺少类型“只读>”的以下属性:历史、位置、匹配 TS2739

请帮助解决此问题

【问题讨论】:

    标签: reactjs typescript react-router-v4


    【解决方案1】:

    您必须将这些道具传递给您的组件。

    你不想在 App 组件中传递它。只需用 react-router 库中的 hoc 包装它)

    高阶组件“withRouter”将完成这项工作

    import { RouteComponentProps, withRouter } from 'react-router';    
    class Routes extends React.Component<RouteComponentProps, any> {
    
      public render() {
        return (
          <div>
            <Switch>
              <Route exact path="/" component={Home} />
              <Route exact path="/login" component={Login} />
              <ProtectedRoute exact path="/admin" component={Admin} />
            </Switch>
          </div>
        );
      }
    }
    
    export default withRouter(Routes);
    

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 1970-01-01
      • 2020-10-17
      • 2020-05-03
      • 2021-01-27
      • 2021-04-02
      • 2021-04-20
      • 2021-07-29
      • 1970-01-01
      相关资源
      最近更新 更多