reactjs - 将路由重定向到“谢谢”组件后,我希望用户能够点击浏览器后退按钮返回主页
问题描述
我有一个简单的 React 应用程序,并且在成功提交表单时使用 React-Router 重定向到感谢组件。这很好用,但是当用户点击浏览器后退按钮或刷新时,它会保持感谢组件的加载,但会删除路由。我在应用程序状态中确实有一个名为“formSubmitted”的变量,当表单提交并显示切换感谢组件的主要主页组件时,它会更改为true。所以我猜这在后退按钮单击或刷新时保持真实。任何帮助,将不胜感激!
我尝试在 IF 语句中使用 PerformanceNavigation.type == 2 或 1 来检查单击,然后将 formSubmitted 的 setState 设置为 false,但没有成功。
Router.js
const Router = () => (
<BrowserRouter>
<Switch>
<Route exact path="/" component={App} />
<Route path="/thank-you" component={App} />
</Switch>
</BrowserRouter>
);
App.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
formSubmitted: false,
zip: "",
};
}
render() {
return (
<div>
<Header/>
{this.state.formSubmitted === false ? (
<div>
<Banner>
<Form/>
</div>
) : (
<ThankYouMessage />
)}
Form.js - This is wrapped with withRouter
fetch(submissionUrl, {
method: "POST",
body: json,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
}).then(response => {
if (response.status >= 200 && response.status < 300) {
this.props.history.push('/thank-you');
return response;
} else {
console.log("Somthing went wrong");
}
});
我不知道是否需要用Router 包装app.js 或最好的方法。
解决方案
您需要将您的 app.js 更改为此,
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
zip: "",
};
}
render() {
return (
<div>
<Header/>
<div>
<Banner>
<Form/>
</div>
</div>
)}
您编写应用程序组件的方式是它还包含该Thankyou
组件。当您将 设置formSubmitted
为 true 时,由于您的条件逻辑,App
组件仍将显示Thankyou
组件而不是Form
.
推荐阅读
- angular - 反应形式中的角度禁用下拉菜单,直到设置另一个下拉菜单中的值
- python - 不确定我的代码使用 symfit 导致 DiracDelta 错误的原因
- python - python打开错误返回“FileNotFoundError:[Errno 2]没有这样的文件或目录:”
- javascript - 传单计算 3 点之间的距离 - 在 javascript 数组对象中搜索
- c++ - 头文件中的外部枚举
- swift - 快速将字符串转换为邮政编码格式
- python - 如何过滤pyspark中的字符串numpy数组列
- algorithm - 将链表重新排列成螺旋链表
- python - 如何在linux中为.py生成编译文件
- ios - iPhone中的Safari - 使用选择的文件对象如果闲置超过约 40 秒,参考将丢失/清除