首页 > 解决方案 > 将路由重定向到“谢谢”组件后,我希望用户能够点击浏览器后退按钮返回主页

问题描述

我有一个简单的 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 或最好的方法。

标签: reactjsreact-router

解决方案


您需要将您的 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.


推荐阅读