如何在使用"history.goBack()"时定义状态



我创建了一些动画,我想用这些动画在我的应用程序中的路由之间导航。 我在某些页面上有一个可见的后退按钮,允许用户弹出导航堆栈以访问最新页面。 我想要两个不同的动画,一个用于在堆栈中更深入地导航,另一个用于弹出回最新页面。 我想使用history.goBack(),但似乎没有办法传递状态从而使用不同的动画。

我使用本文来弄清楚如何为我的组件设置动态动画,但除非我使用history.push({pathname, state:{animation, duration}})否则我看不到如何在用户返回时指定要使用的其他动画。

一种解决方案是将listen方法添加到应用的自定义history对象。 首先按照此处的说明进行设置。

现在,history.goBack()使用历史记录堆栈中的POP操作,因此您可以像这样检查:

import { createBrowserHistory } from 'history';
const history = createBrowserHistory()
history.listen((location, action) => {
if (action === 'POP') {
history.replace(location.pathname, {specialAnimation: 'whatever value'});
}
})
export default history

通过这种方式重写你的状态,如果你的状态中有其他你想要的东西,你可以做一些类似的事情

location.state.specialAnimation = 'whatever';

最新更新