【问题标题】:Keep looping between the last two routes on this simple React app在这个简单的 React 应用程序的最后两条路由之间循环
【发布时间】:2019-12-16 03:20:19
【问题描述】:

我有一个非常简单的项目,您可以在以下位置找到:

https://codesandbox.io/s/issue-looping-between-last-2-routes-xhxu1

存档:/src/store/middlewares.ts 我有以下中间件:

import { Dispatch, Middleware, AnyAction } from "redux";
import { RootState } from "./rootReducer";
import { createStandardAction } from "typesafe-actions";

export const sendMessage = createStandardAction("message/SEND")<string>();

export const locationMiddleware: Middleware<
  {},
  RootState,
  Dispatch<AnyAction>
> = store => next => action => {
  if (action.type === "@@router/LOCATION_CHANGE") {
    store.dispatch(sendMessage("BEFORE D-DAY")); // <--- THIS LINE IS CAUSING THE ISSUE
    const result = next(action);
    store.dispatch(sendMessage("AFTER D-DAY"));
    return result;
  } else {
    return next(action);
  }
};

export const messageMiddleware: Middleware<
  {},
  RootState,
  Dispatch<AnyAction>
> = store => next => action => {
  if (action.type === "message/SEND") {
    console.log("Message: ", action.payload);
  }
  return next(action);
};

如您所见,在每个 @@router/LOCATION_CHANGE 上,我都会发送两个操作,其中包含一条我在另一个中间件上捕获的消息:messageMiddleware,然后我对它们执行 console.log。这些操作在调用之前和之后调度到:next(action)

我面临的问题是:store.dispatch(sendMessage("BEFORE D-DAY"));

启用该行后,您可以执行以下步骤来重现该问题:

  1. 在根位置打开应用(又名:Page 01
  2. 点击链接:Page 02
  3. 点击链接:Page 03
  4. 点击返回按钮(您将被重定向到:Page 02
  5. 单击返回按钮(您将被重定向到:Page 03,而不是 Page 01#FAIL#

请注意,后退按钮是下面的那个(不是浏览器的实际按钮):

另一方面,如果我取消注释我引用为问题的行,则单击后退按钮时行为如预期:-&gt; Page 02 -&gt; Page 01 直截了当。

似乎这个中间件系统不喜欢在调用next(action)之前分派一个动作。

关于如何以一种好的方式解决这种情况并在调用next(action) 之前和之后继续记录操作的任何想法?

要求:使用中间件。

谢谢!

【问题讨论】:

    标签: javascript reactjs redux middleware connected-react-router


    【解决方案1】:

    这个历史对象让我们手动控制浏览器的历史。由于 React Router 是根据当前 URL 更改我们看到的内容,因此历史对象可以让我们对应用程序的某些部分何时何地显示进行细粒度控制。

    1- 创建一个历史对象使用the history package:

    2- 基本用法如下:

    import { createBrowserHistory } from 'history';
    
    const history = createBrowserHistory();
    
    // Get the current location.
    const location = history.location;
    
    // Listen for changes to the current location.
    const unlisten = history.listen((location, action) => {
    // location is an object like window.location
    console.log(action, location.pathname, location.state);
    });
    
    // Use push, replace, and go to navigate around.
     history.push('/home', { some: 'state' });
    
    // To stop listening, call the function returned from listen().
    unlisten();
    

    更多信息enter link description here

    【讨论】:

    • 我正在考虑使用dispatch / middleware 而不是监听器。不过,谢谢。
    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    相关资源
    最近更新 更多