首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >以编程方式导航: React路由器V4+类型脚本出现错误

以编程方式导航: React路由器V4+类型脚本出现错误
EN

Stack Overflow用户
提问于 2019-04-22 23:07:38
回答 2查看 3.1K关注 0票数 3

使用react路由器v4和Typescript以编程方式导航时出错:

只读和子项{

?:ReactNode;}> }类型上不存在历史属性“”history

我想在API调用成功或失败时重定向到特定路径。但无法做到这一点。

路由器代码

import { BrowserRouter as Router , Switch , Route} from 'react-router-dom';
import * as React from 'react';

class App extends React.Component<{}, {}>  {
 render()
 {
    <Router>
      <Switch>
          <Route exact={true} path='/' component={Login}/>
          <Route path='/home' component={Home}/>
          <Route path='/test' component={Test}/>
      </Switch>
    </Router>
  }
}
export default App;

组件

import { withRouter } from "react-router-dom";
import * as React from 'react';

class Test extends React.Component<IProps, IState> {

  handleSubmit = async() => {
            //code for API calls
            this.props.history.push("/home") // error at this line
   }

  render() {
     // Form with validations and a submit handler
  }
}
export default  withRouter(Test);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-23 03:14:49

您需要导入RouteComponentProps界面中包含您正在寻找的道具的import { RouteComponentProps } from "react-router-dom";

export interface RouteComponentProps<Params extends { [K in keyof Params]?: string } = {}, C extends StaticContext = StaticContext, S = H.LocationState> {
  history: H.History;
  location: H.Location<S>;
  match: match<Params>;
  staticContext?: C;
}

您的组件将如下所示:

import { withRouter } from "react-router-dom";
import * as React from "react";
import { RouteComponentProps } from "react-router-dom";
interface IProps {}

type HomeProps = IProps & RouteComponentProps;

interface IState {}

class Home extends React.Component<HomeProps, IState> {
  constructor(props: HomeProps) {
    super(props);
  }
  private handleSubmit = async () => {
    //code for API calls
    this.props.history.push("/home");
  };

  public render(): any {
    return <div>Hello</div>;
  }
}
export const HomeComponent = withRouter(Home);
票数 6
EN

Stack Overflow用户

发布于 2019-10-06 19:39:25

只要你遇到问题就声明它-每次都有效-不幸的是,typescript是一大团泥巴。

如下所示:

const Home: React.FC = (props:any) => {
票数 -4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55796569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档