如何根据时间戳更改 ReactJs 中的路由?

How can I change a route in ReactJs depending on a timestamp?

如何根据时间戳将我的 reactJs menu.js 组件中的路由从一条路由更改为另一条路由。 例如,当它是 12 月 1 日时,以下内容将发生变化:

发件人:

<Link to="/coming-soon">Coming Soon</Link>

收件人:

<Link to="/store">Store</Link>

我正在为 menu.js 使用功能组件,我在 ReactJs 方面经验不多

更新: App.js

  return (
    <>
      <Menu />

      <Switch>
        <Route path="/" exact>
          <LandingPage />
        </Route>
        <Route path="/coming-soon" exact>
          <ComingSoon />
        </Route>
        <Route path="/store" exact>
          <Store />
        </Route>
    </Switch>

    <Footer />
    </>
  );

您可以在时间戳更改时动态设置路由路径,届时您可以像下面这样使用

<Link to="/${yourdynamicpath}">{Title}</Link>

编辑:我注意到您想添加一个检查以在不刷新的情况下更新它,因此我将调整功能组件以将第一个日期存储在 const [currentDate, setCurrentDate] = useState(new Date()) 中并在 useEffect 中以间隔更新例如:

useEffect(() => {
  const interval = setInterval(() => {
     setCurrentDate(new Date())
  }, 1000); // set this as you wish on how responsive you wish it to be
  return () => clearInterval(interval);
}, []);

根据您是否已经安装了日期格式库,确切的实现可能会有所不同,但是例如,如果您使用 date-fns,则会提供许多有用的实用程序,例如:

compareAsc(dateLeft, dateRight)

可以像这样用来比较日期,我们比较今天的日期 new Date() 和 12 月 1 日 new Date('1/12/2021'),如果第一个日期在第二个日期之前它 returns - 1,所以条件为真,我们展示即将到来,如果它在我们之后return 1,条件为假,我们展示商店:

 return (
  <>
    <Menu />
    <Switch>
      <Route path="/" exact>
        <LandingPage />
      </Route>
    </Switch>
    {compareAsc(currentDate, new Date("1/12/2021")) === -1 ? (
      <Route path="/coming-soon" exact>
        <ComingSoon />
      </Route>
    ) : (
      <Route path="/store" exact>
        <Store />
      </Route>
    )}
    <Footer />
  </>
)

并不是说一定要推荐所有东西都打包 - 但对于约会,这些提供了很多方便的实用程序,所以如果你还没有看到它们,那么习惯它们所提供的所有东西会很有用!