以编程方式导航:React Router V4 + Typescript给出错误

时间:2019-04-22 15:07:38

标签: reactjs typescript react-router-v4

使用React Router v4和Typescript进行编程导航时出错:

  

类型'Readonly&Readonly <{children ?: ReactNode; }>

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

2 个答案:

答案 0 :(得分:0)

您需要导入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);

答案 1 :(得分:-1)

只要遇到问题就声明它-每次都可以工作-不幸的是,打字稿是个大难题。

像这样:

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