[英]React with Typescript: Property 'push' does not exist on type 'History'
我试图通过推入历史对象来远离视图。 但是,当我尝试将路由推入其中时,我收到一条错误消息:
“历史”类型不存在“推送”属性。
render(){
return (
<div className="loginWrapper">
withRouter(({history}) => (<button onClick={()=>{history.push('/home')}} className="btn btn-primary">Pieteikties</button>))
</div>
)
}
我能做些什么来解决这个问题?
编辑:
我也试过这个:
logIn(){
this.props.history.push('/new-location')
}
使用这样的组件:
render(){
return (
<div className="loginWrapper">
<button onClick={this.logIn} className="btn btn-primary">Pieteikties</button>
</div>
)
}
它没有用。
更新:我找到了一种新方法来做这种事情。 与 b4 相同,您需要安装它们类型:
1.- npm i react-router react-router-dom
2.- npm i -D @types/react-router @types/react-router-dom
import React from "react";
import { RouteComponentProps } from "react-router-dom";
interface MyComponentProps extends RouteComponentProps {
someOfYourOwnProps: any;
someMorePropsIfNeedIt: any;
}
interface MyComponentState {
someProperty: any;
another: any;
}
export class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
public state: MyComponentState;
public constructor (props: MyComponentProps) {
super(props);
this.state = {
someProperty: "",
another: ""
}
}
public onClickHandler (evt: React.MouseEvent<HTMLButtonElement, MouseEvent>): void {
evt.preventDefault();
}
public componentDidMount () {
this.props.history;
}
public render (): React.ReactElement<MyComponentProps> {
return (
<div>trol</div>
)
}
}
hihitl 我知道发生了什么。 希望你仍然需要它。
1.- npm i react-router react-router-dom
2.- npm i -D @types/react-router @types/react-router-dom
import React from "react";
import { History, LocationState } from "history";
interface MyComponentProps {
someOfYourOwnProps: any;
history: History<LocationState>;
someMorePropsIfNeedIt: any;
}
然后在你的组件上,如果它是一个类做
class MyComponent extends Component<MyComponentProps, {}> {}
如果是函数式
const MyComponent = (props: MyComponentProps) => {}
你在哪里定义history
? 有一个全局window.history
是一个网络标准。 如果您想使用react-router history ,它将作为道具传递。 试试props.history.push()
代替。
该组件必须从反应路由器接收history
道具。 因此,例如,它应该是Route
组件的直接子级,或者您必须通过其父级传递 props。
在 React 16 及更高版本中,您可以使用来自“react-router-dom”的重定向。 在您的情况下,如果您使用重定向而不是历史记录,您将获得相同的结果。
import { Redirect } from 'react-router-dom'
在组件中定义状态
this.state = {
loginStatus:true
}
比在你的渲染方法中
render () {
if(this.state.loginStatus){
return <Redirect to='/home' />
}
return(
<div> Please Login </div>
)
}
编辑:使用 this.props.history
我发现您的代码中缺少两件事。 一种是您的登录方法绑定。 绑定您的方法,以便您可以访问this
。 其他事情是与withRouter
HOC 一起使用。 withRouter
会让你访问 this.history 道具。 像下面这样。
import React from "react";
import { withRouter } from "react-router";
class MainClass extends Component {
constructor(props) {
this.login = this.login.bind(this)
}
logIn(){
this.props.history.push('/new-location')
}
render(){
return (
<div className="loginWrapper">
<button onClick={this.logIn} className="btn btn-
primary">Pieteikties</button>
</div>
)
}
export default withRouter(MainClass);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.