gpt4 book ai didi

reactjs - 在 React-Router v4 中以编程方式导航

转载 作者:行者123 更新时间:2023-12-03 13:28:22 26 4
gpt4 key购买 nike

使用 React Router V4 完成一些验证后,如何移动到新页面?我有这样的东西:

export class WelcomeForm extends Component {

handleSubmit = (e) => {
e.preventDefault()

if(this.validateForm())
// send to '/life'

}
render() {
return (
<form className="WelcomeForm" onSubmit={this.handleSubmit}>
<input className="minutes" type="number" value={this.state.minutes} onChange={ (e) => this.handleChanges(e, "minutes")}/>
</form>
)
}
}

我想将用户发送到另一条路线。我查看了“重定向”,但似乎它会从我不想要的历史记录中删除当前页面。

最佳答案

您正在使用react-router v4 ,所以你需要使用withRouter使用您的组件访问历史对象的属性,然后使用 history.push 动态更改路由。

<强> withRouter :

You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as render props: { match, location, history }.

像这样:

import {withRouter} from 'react-router-dom';

class WelcomeForm extends Component {

handleSubmit = (e) => {
e.preventDefault()
if(this.validateForm())
this.props.history.push("/life");
}

render() {
return (
<form className="WelcomeForm" onSubmit={this.handleSubmit}>
<input className="minutes" type="number" value={this.state.minutes} onChange={ (e) => this.handleChanges(e, "minutes")}/>
</form>
)
}
}

export default withRouter(WelcomeForm);

关于reactjs - 在 React-Router v4 中以编程方式导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44137774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com