反应路由器:userHistory推送功能未按预期工作

问题描述 投票:0回答:1

我正在尝试更改浏览器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个回答
0
投票

好像您已经为自己安排了调度程序。

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

无论您身在何处,上面的代码每300ms(0.3s)都会将URL重置为/home。>>

setTimeOutsetIntervals决不用于路由。所以不要。

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

同样,当您使用<Switch>时,也无需在所有地方都使用exact。在不同情况下,它们只是彼此的替代品。

© www.soinside.com 2019 - 2024. All rights reserved.