【问题标题】:React router: userHistory push function is not working as expectedReact 路由器:userHistory 推送功能未按预期工作
【发布时间】:2020-06-26 00:33:07
【问题描述】:

我正在尝试更改浏览器 URL 并根据某些条件呈现所需的组件。但是,我可以在成功登录后更改 URL 并将用户登陆到 /home 页面,但是当我尝试在按钮单击时更改 URL 时,它会点击 /accounts URL 并再次更改为 /home。

App.js

  <Route exact path="/accounts" component={Accounts} />
  <Route exact path="/home" component={Home} />
  <Route exact path="/" component={Login} />
</Switch>

从组件 A 成功登录后,我正在执行下面的一段代码,该代码呈现家庭组件

 setInterval(() => {
            history.push("/home")
          }, 300);

一旦用户在 /home 中执行按钮单击,我将在下面执行一段代码以更改 url 并呈现帐户组件。

 function showAccountsTransactions () {
        history.replace("/accounts")
    }

  return (
        <div className={classes.root}>
<Fab onClick={showAccountsTransactions}>
                 Show Account and Transactions
        </Fab>
 </div>

但我可以看到 onClick,网址正在更改为 /accounts 并切换回 /home。各位大侠能不能给点意见。

【问题讨论】:

    标签: reactjs react-native react-router browser-history


    【解决方案1】:

    看来您已经为自己准备了一个调度程序。

     setInterval(() => {
                history.push("/home")
              }, 300);
    

    上面的代码每 300 毫秒(0.3 秒)将 URL 重置为 /home,无论您走到哪里。

    setTimeOutsetIntervals 永远不会用于路由。所以不要。

    还有一些最佳做法是避免使用history.replace(),而改用history.push()。更改路线的历史堆栈不是一个正确的想法。

    同样当你使用&lt;Switch&gt; 时,没有必要在任何地方都使用exact。它们只是在不同情况下的替代品。

    【讨论】:

    • 感谢精彩的解释。我没有注意到那个愚蠢的错误。我已经按照您的建议进行了所有更改,并且效果很好
    猜你喜欢
    • 2014-05-02
    • 2013-08-29
    • 2016-08-19
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2021-08-27
    相关资源
    最近更新 更多