React 使用 RouteComponentProps - 类型 '{}' 缺少类型 'Readonly<RouteComponentProps<{} 中的以下属性 [英] React Use RouteComponentProps - Type &#39;{}&#39; is missing the following properties from type &#39;Readonly&lt;RouteComponentProps&lt;{}

查看:58
本文介绍了React 使用 RouteComponentProps - 类型 '{}' 缺少类型 'Readonly<RouteComponentProps<{} 中的以下属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

export default class Routes extends Component{使成为() {返回 (<div><开关><路由精确路径="/" component={Home}/><路由精确路径="/login" component={Login}/><ProtectedRoute 精确路径="/admin" component={Admin}/></开关>

);}}

当我使用 props 接口作为 RouteComponentProps 时,它在下面的代码中给我错误.

class App 扩展组件 {使成为() {返回 (<提供者><React.Fragment><导航栏/><路线/></React.Fragment></提供者>);}}

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

类型{}"缺少类型只读>"中的以下属性:历史记录、位置、匹配 TS2739

请帮忙解决这个问题

解决方案

你必须将这些 props 传递给你的组件.

ofc 你不想在 App 组件中传递它.只需用来自 react-router 库的 hoc 包装它

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

import { RouteComponentProps, withRouter } from 'react-router';Routes 类扩展了 React.Component{公共渲染(){返回 (<div><开关><路由精确路径="/" component={Home}/><路由精确路径="/login" component={Login}/><ProtectedRoute 精确路径="/admin" component={Admin}/></开关>

);}}导出默认 withRouter(Routes);

I am using React with Typescript and needs to use the history for that I need to have interface of 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>
  );
 }}

When I use the props interface as RouteComponentProps it gives me error at below code.

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

Error comes when I try to use my Route Component. The error says

Type '{}' is missing the following properties from type 'Readonly>': history, location, match TS2739

Kindly help in resolving this issue

解决方案

you have to pass these props to your component.

ofc you dont want to pass it in App component. Just wrap it with hoc from react-router lib)

high order component "withRouter" will do the job

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);

这篇关于React 使用 RouteComponentProps - 类型 '{}' 缺少类型 'Readonly<RouteComponentProps<{} 中的以下属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆