使用Redux中间件控制React路由器导航

7ivaypg9  于 2022-11-24  发布在  React
关注(0)|答案(4)|浏览(174)

在Redux中间件功能的帮助下,我在离开播放页面时显示警告模式。
问题是我不能控制导航在这一点上。页面被改变之前,模态是显示出来。
有什么方法可以阻止路由器导航,并根据模式选择来决定吗?

middleware.push(routeIntrerceptor);

.....

const routeIntrerceptor = ({dispatch, getState}) => next => action => {
  const state = getState();
  const location = state.router.location.pathname;

  if (action.type === '@@router/LOCATION_CHANGE' && location.includes('play')) {
    dispatch({ type: 'SET_DIALOG_TOGGLE' });
  }
  next(action);
};

export default routeIntrerceptor;
jyztefdp

jyztefdp1#

如果你想阻止用户离开一个页面,你可以使用<Prompt />,它与react-router一起提供。
检查react-router -的文档
https://reacttraining.com/react-router/web/example/preventing-transitions

o4tp2gmn

o4tp2gmn2#

您可以采用不同的方法,使用Route呈现方法而不是中间件。
您可以创建shouldRender函数,并在切换到其他页面之前对其进行检查。
第一个

ckx4rj1h

ckx4rj1h3#

我最终使用了react-router-navigation-prompt,因为我需要对<Prompt/>进行样式化。
然而,这并没有回答我关于redux中间件解决方案的问题。

2j4z5cfb

2j4z5cfb4#

试着回应一个承诺:

middleware.push(routeIntrerceptor);
    
.....

const routeIntrerceptor = ({dispatch, getState}) => next => action => {
  const state = getState();
  const location = state.router.location.pathname;

  if (action.type === '@@router/LOCATION_CHANGE' && location.includes('play')) {
    dispatch({ type: 'SET_DIALOG_TOGGLE' });
    return Promise.resolve();
  }
  next(action);
};

export default routeIntrerceptor;

相关问题