【问题标题】:Programmatically navigating : React Router V4+ Typescript giving error以编程方式导航:React Router V4+ Typescript 给出错误
【发布时间】:2019-09-11 18:35:10
【问题描述】:

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

“只读”和“只读”类型上不存在属性“历史”

我想在 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);

【问题讨论】:

标签: reactjs typescript react-router-v4


【解决方案1】:

您需要导入import { RouteComponentProps } from "react-router-dom"; RouteComponentProps 接口有你要找的道具。

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

【讨论】:

  • 完美!非常感谢
  • 在传递props时如何调用组件?
【解决方案2】:

只要遇到问题就声明它 - 每次都有效 - 不幸的是,打字稿是一团泥。

像这样:

const Home: React.FC = (props:any) => {

【讨论】:

  • 这是一个非常糟糕的做法,请尽量避免使用any 类型。否则,就意味着你无缘无故地使用 TypeScript。
猜你喜欢
  • 2017-10-23
  • 2018-04-04
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多