以编程方式导航:React Router V4+ Typescript 给出错误 [英] Programmatically navigating : React Router V4+ Typescript giving error
本文介绍了以编程方式导航:React Router V4+ Typescript 给出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 react router v4 和 Typescript 以编程方式导航时出错:
Error while programmatically navigating using react router v4 and Typescript:
只读"和只读"类型不存在历史记录"属性Readonly<{ children?: ReactNode;}>
Property 'history' does not exist on type 'Readonly & Readonly<{ children?: ReactNode; }>
我想在 API 调用成功或失败时重定向到特定路径.但无法做到这一点.
I want to redirect to a particular path on success or failure of a API call. But Unable to do that.
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);
推荐答案
您需要导入 import { RouteComponentProps } from "react-router-dom";
RouteComponentProps 接口包含您正在寻找的道具.
You need to import the import { RouteComponentProps } from "react-router-dom";
The RouteComponentProps interface has the props you're looking for.
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);
这篇关于以编程方式导航:React Router V4+ Typescript 给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文