我试图通过推入历史对象来离开视图。但是,当我尝试将路由推送到其中时,我收到一条错误消息:
属性"push"在类型"历史记录"上不存在。
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>
)
}
}
希希尔 我知道发生了什么。希望你需要它。
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
它是一个Web标准。如果你想使用反应路由器的历史记录,它作为一个道具传递。请尝试props.history.push()
。
组件必须从反应路由器接收history
道具。因此,例如,它应该是Route
组件的直接子组件,或者您必须通过其父级传递道具。
在 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>
)
}
编辑:使用这个.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);