使用 React Router v4,如何使用
goBack()
方法区分 goForward()
和 listen()
调用?
据我所知,
location
和 action
参数没有提供足够的信息来区分。 action
参数对于后退和前进都是 POP
。
history.listen((location, action) => {
// action = 'POP' when goBack() and goForward() are called.
}
我正在使用 history 节点模块。
我有一个面包屑组件,其项目保存在状态中。当用户返回时,我需要弹出最后一个面包屑。
您可以从数组中的
key
对象收集所有 location
值,并使用它来确定键是否按顺序出现在前一个值之前或之后,并使用它来区分 goBack
和 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);
React Router Dom v6 更新:
import { useNavigate } from "react-router-dom";
export const App = () => {
const navigate = useNavigate();
const handleClickHome = () => {
navigate("/home");
}
const handleClickBack = () => {
navigate(-1);
}
const handleClickForward = () => {
navigate(1);
}
return (
<div>
<button onClick={handleClickHome}>Go Home</button>
<button onClick={handleClickBack}>Go Back</button>
<button onClick={handleClickForward}>Go Forward</button>
</div>
);
}