简体   繁体   English

Redux Thunk vs Redux 自定义中间件

[英]Redux Thunk vs Redux custom Middleware

I am new to redux.我是 redux 的新手。 So after reading lots of tutorials.I understood that, redux need redux thunk to dispatch async actions by returning another function.But if I call http request inside custom middle-ware then So after reading lots of tutorials.I understood that, redux need redux thunk to dispatch async actions by returning another function.But if I call http request inside custom middle-ware then

  1. is it required redux thunk?是否需要 redux thunk?
  2. is Redux custom middleware no side effects? Redux自定义中间件没有副作用吗? I mean no need to return another function.我的意思是不需要返回另一个 function。

If i use redux thunk then my action creator looks like this.如果我使用 redux thunk 那么我的动作创建者看起来像这样。 This I understood这我明白了

function incrementAsync() {
  return (dispatch) => {
    setTimeout(() => {
      // Yay! Can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 1000);
  };
}

I have confusion in custom middle-ware.我对自定义中间件感到困惑。

https://blog.logrocket.com/managing-asynchronous-actions-in-redux-1bc7d28a00c6/ https://blog.logrocket.com/managing-asynchronous-actions-in-redux-1bc7d28a00c6/

as per this blog根据这个博客

const httpMiddleware = store => next => action => {
  if (action[HTTP_ACTION]) {
    const actionInfo = action[HTTP_ACTION];
    const fetchOptions = {
      method: actionInfo.verb,
      headers: actionInfo.headers,
      body: actionInfo.payload || null
    };

    next({
      type: actionInfo.type + "_REQUESTED"
    });

    fetch(actionInfo.endpoint, fetchOptions)
      .then(response => response.json())
      .then(data => next({
        type: actionInfo.type + "_RECEIVED",
        payload: data
      }))
      .catch(error => next({
        type: actionInfo.type + "_FAILED",
        payload: error
     }));
  } else {
    return next(action);
  }
}

they are not returning any dispatch function inside action.他们没有返回任何调度 function 内部操作。 I know that store,next,action are the inner functions.我知道 store,next,action 是内部函数。

can any one help me to understand about this?任何人都可以帮助我了解这一点吗?
Thank you.谢谢你。

All redux-thunk is is a simple redux middleware that checks if your action is a function and acts accordingly.所有redux-thunk都是一个简单的 redux 中间件,它检查您的操作是否是 function 并采取相应措施。 You can build it yourself in 5 minutes.您可以在 5 分钟内自己构建它。

You can see that it deconstructs dispatch and getState from the store object, and then calls your action with them as parameters.您可以看到它从存储 object 中解构了dispatchgetState ,然后将它们作为参数调用您的操作。

Have a look at it'ssource code .看看它的源代码

So, your example code can look like this:因此,您的示例代码可能如下所示:

const httpMiddleware = store => next => action => {
  if (action[HTTP_ACTION]) {
    const actionInfo = action[HTTP_ACTION];
    const fetchOptions = {
      method: actionInfo.verb,
      headers: actionInfo.headers,
      body: actionInfo.payload || null
    };

    store.dispatch({
      type: actionInfo.type + "_REQUESTED"
    });

    fetch(actionInfo.endpoint, fetchOptions)
      .then(response => response.json())
      .then(data => store.dispatch({
        type: actionInfo.type + "_RECEIVED",
        payload: data
      }))
      .catch(error => store.dispatch({
        type: actionInfo.type + "_FAILED",
        payload: error
     }));
  } else {
    return next(action);
  }
}

As you asked by point list I'm gonna reply by point list:正如您按点列表询问的那样,我将按点列表回复:

  • If i call http request inside custom middleware then is it required redux thunk?如果我在自定义中间件中调用 http 请求,那么是否需要 redux thunk?

Redux thunk is a middleware per se, it's recommended if you want to dispatch an action that make (let's say, for example) an AJAX call and dispatch two different action based on the result of that AJAX call, one if it fails and one if it succeeds. Redux thunk 本身就是一个中间件,如果您想调度一个动作(例如)进行 AJAX 调用并根据该 ZA34A6659BCEAE7ABFCA5Z 调用的结果调度两个不同的动作,如果一个 if 一个 if 一个 if 一个 if 一个 if 一个 if 一个失败,那么它是推荐的它成功了。

  • is Redux custom middleware no side effects? Redux自定义中间件没有副作用吗? i mean no need to return another function.我的意思是不需要返回另一个 function。

If I'm understanding correctly: A middleware will simply take the action you dispatched and pass it through the chain, it'll let you do something before sending the action to the reducer "phase".如果我理解正确:中间件将简单地接受您调度的操作并将其传递给链,它会让您在将操作发送到减速器“阶段”之前做一些事情。 What it'll do is entirely up to you.它会做什么完全取决于你。 You need at least to do next(action) or block the action based on some logic, if needed.如果需要,您至少需要根据某些逻辑执行下一步(操作)或阻止操作。

Finally, a custom middleware like the one you posted is modifying the action you passed based on the response of an AJAX call, making it more of an "interceptor" than a simple middleware.最后,像您发布的那样的自定义中间件正在根据 AJAX 调用的响应修改您传递的操作,使其更像是一个“拦截器”而不是一个简单的中间件。 Written this way, it's not dispatching a new action, it's more related to modifying the action you passed.这么写,不是派发新的动作,更多的是与修改你传递的动作有关。

If you want to dispatch a new action based on the result of an ajax call, but without creating a middleware/interceptor, you could do it this way:如果您想根据 ajax 调用的结果调度新操作,但不创建中间件/拦截器,您可以这样做:

const postSomethingAction = postObject => {
    return async dispatch => {
        dispatch(postSomethingPending())
        const response = await Api.postSomething(postObject)
        if (response.message) {
            dispatch(postSomethingError(response))
        }
        else {
            dispatch(postSomethingSuccess(response.data))
        }
    }
}

In this example we're using Thunk do create an action that dispatch another action based on the result of Api.postSomething在这个例子中,我们使用 Thunk 创建一个动作,根据Api.postSomething的结果调度另一个动作

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

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