【问题标题】:React Router -- Differentiate goBack() and goForward() in listen()React Router——在listen()中区分goBack()和goForward()
【发布时间】:2018-08-13 15:14:37
【问题描述】:

问题

使用 React Router v4,我如何区分使用 listen() 方法的 goBack()goForward() 调用?

据我所知,locationaction 参数没有提供足够的信息来区分。 action 参数是 POP 用于后退和前进。

history.listen((location, action) => {
  // action = 'POP' when goBack() and goForward() are called.
}

我正在使用history 节点模块。

目的

我有一个面包屑组件,其项目处于状态。当用户返回时,我需要弹出最后一个面包屑。

【问题讨论】:

    标签: javascript reactjs react-router react-router-v4


    【解决方案1】:

    您可以从数组中的location 对象中收集所有key 值,并使用它来确定键是按顺序位于前一个之前还是之后,并使用它来区分goBackgoForward.

    示例

    const keys = [];
    let previousKey;
    
    history.listen((location, action) => {
      const { key } = location;
    
      // If there is no key, it was a goBack.
      if (key === undefined) {
        console.log('goBack')
        return;
      }
    
      // If it's an entirely new key, it was a goForward.
      // If it was neither of the above, you can compare the index 
      // of `key` to the previous key in your keys array.  
      if (!keys.includes(key)) {
        keys.push(key);
        console.log('goForward');
      } else if (keys.indexOf(key) < keys.indexOf(previousKey)) {
        console.log('goBack');
      } else {
        console.log('goForward');
      }
    
      previousKey = key;
    });
    
    history.push("/test");
    history.push("/test/again");
    setTimeout(() => history.goBack(), 1000);
    setTimeout(() => history.goBack(), 2000);
    setTimeout(() => history.goForward(), 3000);
    

    【讨论】:

    • 你真是个天才!
    猜你喜欢
    • 2020-09-26
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2014-09-02
    • 2017-08-28
    相关资源
    最近更新 更多