goo*_*eon 5 javascript reactjs react-router react-router-v4
使用 React Router v4,如何区分goBack()和goForward()调用listen()方法?
据我所知,location和action参数没有提供足够的信息来区分。该action参数是POP两个前进和后退。
history.listen((location, action) => {
// action = 'POP' when goBack() and goForward() are called.
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 历史节点模块。
我有一个面包屑组件,其项目保持在状态。当用户返回时,我需要弹出最后一个面包屑。
您可以key从location数组中的对象中收集所有值,并使用它来确定键是按顺序出现在前一个之前还是之后,并使用它来区分 agoBack和goForward。
例子
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3565 次 |
| 最近记录: |