javascript - 如何在 React 中使用 history.push 导航
问题描述
我可以将我的组件名称添加到:例如:this.props.history.push(<Sample/>)
我有一个关于在此添加路径的想法:this.props.history.push("/Sample")
.
或者如何将其导航到我的组件:
.catch((error) => {
console.log("error", error);
this.setState({
finishedStep: false,
});
this.props.history.push("<Sample/>");
});
如果完成的步骤是false
,我想将其导航到我的<Sample>
组件。
解决方案
假设您已经为<Sample />
Component 配置了相应的路由。
用react-router-dom
安装 - react-router-dom
npm install --save react-router-dom
例子:
import { withRouter } from 'react-router-dom';
class YourComponent extends React.Component {
handleSubmit = (user) => {
saveUser(user).then(() =>
this.props.history.push('/dashboard')
)).catch((error) => {
console.log("error", error);
this.setState({
finishedStep: false,
});
this.props.history.push("/Sample");
})
}
render() {
return (
<div>
<Form onSubmit={this.handleSubmit} />
</div>
)
}
}
export default withRouter(YourComponent)
您可以不使用的另一种方法react-router-dom
是。
render() {
if (this.state.finishedStep === false) {
return <Redirect to='/Sample' />
}
return (
<div>
<Form onSubmit={this.handleSubmit} />
</div>
)
}
推荐阅读
- angular - 在 Angular 8 上创建画布以绘制签名时遇到问题
- go - 禁用“慢速测试”的银杏警告
- python - 如何绘制显示数据变化量的时间序列?
- c++ - openmp 嵌套循环处理性能
- kubernetes - Kubernetes Nginx Ingress 未正确重定向到路径路由服务
- node.js - node.js 中的 TEAMS 机器人:CreateConversation 方法中的“此请求的授权已被拒绝”
- excel - 如何根据每月用户数据在 Excel 中创建历史数据库
- android - 使APP android读取文件的内容 - IONIC
- node.js - 如何使用 Winston 库在 Node.js 中每天将 logrotate 日志记录到单独的文件中
- c++ - 为什么调用模板类函数时会出现 SEGFAULT?