简体   繁体   English

Redux Promise和Redux Promise Middleware有什么意义?

[英]What is the point of Redux Promise and Redux Promise Middleware?

I've searched high and low but can't find a clear answer. 我搜索了高低,但找不到明确的答案。

I've managed to wrap my head around the mechanics of Redux, but when I've come to the point of API calls and async action creators, I'm stuck with middleware in context of Promises. 我已经设法绕过Redux的机制, 但是当我到了API调用和异步动作创建者的角度时,我在Promises的上下文中遇到了中间件。

Can you help me get the mess right? 你能帮我搞清楚吗?

Cotradictory pieces of the puzzle giving me headache: Cotradictory这个拼图让我头疼:

  1. One of YT tutorials says that natively Redux dispatch method does not support promises returned from action creators--hence the need for Redux Promise library (I know the project is probably dead now and the continuation is Redux Promise Middleware). YT教程之一说,本机Redux调度方法不支持从动作创建者返回的promise - 因此需要Redux Promise库(我知道项目现在可能已经死了,延续是Redux Promise Middleware)。

  2. Dan says in " What is the difference between redux-thunk and redux-promise? " I can use promises even without middleware--just manage them in the action creator. Dan在“ redux-thunk和redux-promise之间有什么区别? ”我说,即使没有中间件,我也可以使用promises - 只需在动作创建者中管理它们。

  3. In other answers I found examples of using thunks where the action creator returned a... promise (later is was processed in the caller / dispatch(myActionCreator(params).then(...) / So a promise can be returned by a thunk WITHOUT any redux-promise lib..? 在其他答案中,我找到了使用thunks的例子,其中动作创建者返回了一个... promise (后来是在调用者/ dispatch中处理的(myActionCreator(params).then(...) /所以一个promise 可以返回一个thunk 没有任何redux-promise lib ..?

  4. In " What is the difference between redux-thunk and redux-promise? ", the accepted answer states Redux Thunk returns functions, whereas Redux Promise returns promises.. what the heck? 在“ redux-thunk和redux-promise之间有什么区别? ”,接受的答案表明Redux Thunk返回函数,而Redux Promise返回promises ..到底是什么?

To wrap it up: what's the point of using Redux Promise or Redux Promise Middleware? 总结一下:使用Redux Promise或Redux Promise Middleware有什么意义? Why does Redux alone not natively support promises? 为什么Redux本身不支持承诺?

Update: 更新:

I've just realized that in point 3 above I overlooked then() being attached to dispatch and not included in dispatch() args. 我刚刚意识到在上面的第3点我忽略了then() 附加dispatch而不包括dispatch() args中。

The linked answers are correct, but I'll try to explain further. 链接的答案是正确的,但我会尝试进一步解释。

A basic Redux store will only accept dispatching plain object actions: 基本的Redux存储接受调度普通对象操作:

store.dispatch({type : "ADD_TODO", text : "Buy milk"});

If you try to pass anything other than a plain object action, the store will throw an error: 如果您尝试传递除普通对象操作以外的任何内容,则存储将抛出错误:

store.dispatch(() => {});
// Error: "Actions must be plain objects. Use custom middleware for async actions."

Middleware form a pipeline around store.dispatch() , and each middleware can do anything it wants with whatever value was passed to dispatch : modify it, log it, delay it, or dispatch something else instead it . 中间件围绕store.dispatch()形成一个管道 ,每个中间件都可以做任何事情,无论传递给dispatch任何值: 修改它,记录它,延迟它,或者发送其他东西而不是它 That means that a middleware can "teach" dispatch() how to accept something that's not a plain action object, by intercepting the value and doing something else instead. 这意味着中间件可以“教导” dispatch()如何接受不是普通操作对象的东西,通过拦截值并做其他事情。

So, redux-thunk "teaches" dispatch how to accept functions, by intercepting the function and calling it instead of passing it on to the reducers. 所以, redux-thunk “教” dispatch如何接受函数,通过拦截函数并调用它而不是将它传递给reducers。 redux-promise "teaches" dispatch how to accept promises, by intercepting the promise and dispatching actions when the promise resolves or rejects. redux-promise “教导”通过在承诺解决或拒绝时拦截承诺和派遣行动来dispatch如何接受承诺。

Normally, dispatch returns whatever action object was passed in. Because middleware wrap around dispatch , they can also change what value is being returned. 通常, dispatch返回传入的任何操作对象。由于中间件环绕dispatch ,它们还可以更改返回的值。 redux-thunk will run the thunk function, and return whatever that thunk function returns. redux-thunk将运行thunk函数,并返回thunk函数返回的任何内容。 That lets you do useful things like return a promise from a thunk, and chain behavior from there: 这可以让你做一些有用的事情,比如从thunk返回一个promise,以及从那里返回链接行为:

dispatch(someThunkReturningAPromise())
    .then(() => {
        // Do more stuff here
    });

For more info on the topic, see the Redux FAQ entry on dealing with side effects , and the articles in the Redux Side Effects section of my React/Redux links list . 有关该主题的更多信息,请参阅有关处理副作用Redux FAQ条目 ,以及React / Redux链接列表Redux Side Effects部分中的文章。

When you call an action creator, one the very first line of the action creator function, you make the ajax request. 当您调用动作创建者(动作创建者函数的第一行)时,您将发出ajax请求。 That's a network request that is going to reach out to that JSON API. 这是一个将要访问该JSON API的网络请求。

The key part to understand is that when we make that request, we go down to the next line of code where we form up that action object and return it. 要理解的关键部分是,当我们提出请求时,我们将转到下一行代码,我们将构成该操作对象并将其返回。 The time between those two steps, between making the request and returning the action is instantaneous. 这两个步骤之间的时间,即发出请求和返回动作之间的时间是即时的。

As you very well know, whenever we make a network request to some outside API, it may take some amount of time to get a response back. 众所周知,每当我们向某些外部API发出网络请求时,可能需要一些时间才能获得响应。

So, after we return our action from the action creator, at some point in the future, we get a response back from the JSON API. 因此,在我们从动作创建者返回动作之后,在将来的某个时刻,我们会从JSON API获得响应。

So, between Ajax request issued and Action returned from action creator may be instantaneous, but the time between Action being returned from action creator and response from JSON API received may take longer. 因此,在发出的Ajax请求和从动作创建者返回的Action之间可能是即时的,但是从动作创建者返回的Action与从JSON API返回的响应之间的时间可能需要更长的时间。

Regardless how long it takes, by the time the action shows up inside of the reducer, it always has our data available from our API. 无论需要多长时间,当动作出现在减速器内部时,它总是从我们的API中获得我们的数据。

To give you a better idea, I have added a debugger statement to one of my own reducers so we can look at the different values inside of there. 为了给你一个更好的想法,我在我自己的一个reducer中添加了一个debugger语句,这样我们就可以查看其中的不同值。

import { SAVE_COMMENT, FETCH_COMMENTS } from 'actions/types';

export default function(state = [], action) {
  switch (action.type) {
    case SAVE_COMMENT:
      return [...state, action.payload];
    case FETCH_COMMENTS:
      debugger;
      const comments = action.payload.data.map(comment => comment.name);
      return [...state, ...comments];
    default:
      return state;
  }
}

在此输入图像描述

When I clicked the Fetch Comments button thats when it called the action creator and inside my sources tab I immediately hit the debugger statement. 当我在调用动作创建器时单击“获取注释”按钮时,在我的“源”选项卡中,我立即点击了debugger语句。

Here is evidence that whenever this action shows up inside a reducer, it has the response that it got from the API. 以下证据表明,只要此操作出现在reducer中,它就会从API获得响应。

在此输入图像描述

Now, lets remove the Redux Promise middleware and see what happens. 现在,让我们删除Redux Promise中间件,看看会发生什么。

Middleware: 中间件:

export default ({ children, initialState = {} }) => {
  const store = createStore(
    reducers,
    initialState,
    applyMiddleware(reduxPromise)
  );

Middleware gone: 中间件消失了:

export default ({ children, initialState = {} }) => {
  const store = createStore(reducers, initialState, applyMiddleware());

  return <Provider store={store}>{children}</Provider>;
};

What's this? 这是什么?

在此输入图像描述

The payload is not a response coming back from the JSON API, instead its a pending Promise , which means our request is still out on the network waiting to come back from the JSON API. payload不是从JSON API返回的响应,而是一个挂起的Promise ,这意味着我们的请求仍然在网络上等待从JSON API返回。 So clearly, without Redux Promise middleware, our application will not work as expected. 很明显,如果没有Redux Promise中间件,我们的应用程序将无法按预期工作。

Action creators were not developed to support asynchronous request, call it an oversight, I don't know. 动作创建者没有开发支持异步请求,称之为疏忽,我不知道。

We use middlewares like Redux Promise to look at actions that are about to be sent to a reducer and we have the opportunity to delay, log, modify or stop the action entirely and its only through these middlewares that we make these asynchronous requests work the way we expect it to. 我们使用像Redux Promise这样的中间件来查看即将发送到reducer的操作,我们有机会完全延迟,记录,修改或停止操作,并且只能通过我们使这些异步请求以这些方式工作的中间件我们期待它。 We are using Redux Promise because we want to inspect every action returned from an action creator and if it contains an API request or some asynchronous request, we want to delay it, so we can get that response to come back before the action goes on to the reducers. 我们正在使用Redux Promise,因为我们要检查从动作创建者返回的每个动作,如果它包含API请求或某个异步请求,我们想要延迟它,所以我们可以在动作继续之前得到响应减速器。 That is what Redux Promise does for us. 这就是Redux Promise为我们所做的事情。

you need those middlewares in order to avoid race conditioning because javascript is async. 你需要那些中间件以避免竞争条件,因为javascript是异步的。 The differences between them are just the implementation, thunk works with functions, sagas with generators, etc 它们之间的区别仅在于实现,thunk与函数一起工作,sagas与生成器等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM