简体   繁体   English

redux-thunk的唯一好处是什么?

[英]What is the sole benefit of redux-thunk?

I am relatively newer to redux. 我对redux较新。 I have gone through a lot of article still i am not getting a clear picture whats the real benefit of using redux-thunk . 我已经阅读了很多文章,但我仍然不清楚,使用redux-thunk的真正好处是什么。

All I understood is it allows you to return a function instead of object from action-creators ? 我所了解的是,它允许您从action-creators返回函数而不是对象? But what's the benefit? 但是有什么好处呢? I have created few small react projects without using redux-thunk. 我没有使用redux-thunk创建了一些小型的React项目。

Let's consider the below snippets. 让我们考虑以下片段。 Both behaves the same. 两者的行为相同。

It would be great help if someone can explain me or point me to the correct resources to get a better understanding. 如果有人可以向我解释或将我指向正确的资源以获得更好的理解,那将是非常有帮助的。

With redux-thunk

 export function fetchContacts(){ return function(dispatch){ axios .get('/contacts') .then( contacts => dispatch({ type: 'FETCH_CONTACTS', payload: contacts})) } } 

Without redux-thunk

 const client = axios.create({ baseURL: "http://localhost:3000", headers: { "Content-Type": "application/json" } }) const url = '/contacts'; export function fetchContacts(){ return { type: 'FETCH_CONTACTS', payload: client.get(url) } } 

redux-thunk allows you to execute asynchronous operations. redux-thunk允许您执行异步操作。

In your first example you are sending the actual data returned by your API endpoint to your reducer. 在第一个示例中,您正在将API端点返回的实际数据发送到reducer。 And the action will only be sent after the server has returned the data. 并且仅在服务器返回数据之后才发送操作。

In your second example, you are sending a promise to your reducer which doesn't work as you would have to resolve your promise inside the reducer, which breaks the principle upon which reducers should be pure functions. 在第二个示例中,您向减速器发送了一个诺言,该诺言不起作用,因为您必须在减速器中解决诺言,这打破了简化器应为纯函数的原则。

The purpose of Redux itself, is to hold our application state. Redux本身的目的是保持我们的应用程序状态。 One of the great features of Redux is that we can change our state in a well-defined pattern and it's a pattern that we repeat over and over in our applications. Redux的一大特色是我们可以按照定义良好的模式更改状态,并且这种模式可以在应用程序中一遍又一遍地重复。

We call an Action Creator , this produces an Action . 我们称一个动作创建者 ,它产生一个动作 The Action flows into our Middleware , then our Reducers which then flows into our application State then into React . Action流入我们的中间件 ,然后进入我们的Reducer ,然后进入我们的应用程序状态,然后进入React Then we sit around and wait for the user to initiate some change inside of our application that repeats the process all over again. 然后,我们坐在那里等待用户在我们的应用程序内发起一些更改,从而再次重复该过程。

This process works fine with any kind of synchronous change. 此过程适用于任何类型的同步更改。 By synchronous I mean that we call an Action Creator which immediately flows into an Action , Middleware and our Reducers . 通过同步,我的意思是我们称为动作创建者 ,该动作创建者立即流入动作中间件和我们的Reducer

The vast majority of web applications we build, however, need to fetch data from asynchronous channels. 但是,我们构建的绝大多数Web应用程序都需要从异步通道中获取数据。 In other words, its more common to call an Action Creator that is fetching data from an API or some asynchronous action and only when that request resolves are we actually ready to create an Action . 换句话说,调用从API或某些异步操作中获取数据的Action Creator更为常见,并且只有在该请求解析后,我们才真正准备好创建Action

Vanilla Redux is not setup to handle this out of the box. 未设置Vanilla Redux来开箱即用。

So, how do we handle these asynchronous Action Creators ? 那么,我们如何处理这些异步动作创建者呢?

This is where Redux-Thunk comes into play. 这就是Redux-Thunk发挥作用的地方。 The purpose of Redux-Thunk is to give us direct control over the Dispatch method. Redux-Thunk的目的是让我们直接控制Dispatch方法。 The Dispatch method is part of the ReduxStore that contains our application state. Dispatch方法是ReduxStore的一部分,它包含我们的应用程序状态。

The Dispatch method handles: Dispatch方法处理:
Middleware 中间件
Reducers 减速器
State

When we normally call an Action Creator and it returns an Action , the Action ends up being returned into this Dispatch method. 当我们通常调用Action Creator并返回Action时 ,该Action最终返回到此Dispatch方法中。 You have been using the Dispatch method behind-the-scenes in vanilla Redux. 您一直在香草Redux的幕后使用Dispatch方法。

So in practice, say you have a file in actions/index.js : 所以在实践中,假设您在actions/index.js有一个文件:

import axios from 'axios';

export function fetchUsers() {
   const request = axios.get('http://somejsondata.com/users');
}

Redux expects us to return an action, but we do not yet have any data. Redux期望我们返回一个动作,但是我们还没有任何数据。 I have to wait for my request to resolve before I have any data to send across to my Dispatch method. 在将任何数据发送到我的Dispatch方法之前,我必须等待请求解决。

So, lets use Redux-Thunk where all the existing rules for action creators kind of go out the window. 因此,让我们使用Redux-Thunk吧,其中动作创建者的所有现有规则都可以忽略。 Redux expects for us to return an Action which is a plain JavaScript object. Redux期望我们返回一个Action ,它是一个纯JavaScript对象。

Redux-Thunk enables one other return type, which is a plain JavaScript function. Redux-Thunk启用了另一个返回类型,这是一个普通的JavaScript函数。

import axios from 'axios';

export function fetchUsers() {
   const request = axios.get('http://somejsondata.com/users');

   return () => {

   };
}

The first argument is going to be the dispatch method: 第一个参数将是dispatch方法:

import axios from 'axios';

export function fetchUsers() {
   const request = axios.get('http://somejsondata.com/users');

   return (dispatch) => {

   };
}

If we pass an Action into dispatch , it's going to be sent off to all our different reducers . 如果我们将一个Action传递到dispatch ,它将被发送给所有不同的reducer

export function fetchUsers() {
       const request = axios.get('http://somejsondata.com/users');

       return (dispatch) => {
         request.then(({data}) => {
           dispatch({type: 'FETCH_PROFILES', payload: data})
         });
       };
    }

This is saying, we are going to wait for request to resolve with some amount of data and only when it has will I dispatch an action. 这就是说,我们将等待请求处理一些数据,并且只有在请求得到处理后,我才会调度操作。 In this case, it is going to have type FETCH_PROFILES and payload of data . 在这种情况下,它将具有FETCH_PROFILES typedata payload

redux-thunk allows you to delay your actions in order to make async calls before dispatching. redux-thunk允许您延迟操作,以便在分派之前进行异步调用。 lets say you are retrieving user settings. 可以说您正在检索用户设置。 the common use-case is to dispatch a REQUEST_FOR_USER_SETTINGS_IN_PROGRESS action so you can show a loader in your app, then make the http request for the data and when you get a response, dispatch a SUCCESS or ERROR action to update UI. 常见用例是调度REQUEST_FOR_USER_SETTINGS_IN_PROGRESS操作,以便您可以在应用中显示加载程序,然后对数据进行http请求,并在收到响应时调度SUCCESS或ERROR操作以更新UI。 it would look something like this: 它看起来像这样:

const requestToGetCoins = await() => {
return (dispatch) => {
    dispatch(requestToGetUserSettingsInProgress());
    try{
      const users = async httpService.getUserSettings();
      dispatch(requestToGetUserSettingsSuccess(users));
    }
    catch(e){
      dispatch(requestToGetUserSettingsError(e));
    }
};

}; };

just wanted to emphasise that there is a better way to handle async actions in redux than redux-thunk, using an adhoc middleware which handles async actions and reduces much of the boilerplate. 只是想强调一点,使用即席中间件来处理redux中的异步动作比redux-thunk更好,它可以处理异步动作并减少很多样板。 I suggest you take a look at this: https://medium.com/@sht_5/minimal-code-for-redux-async-actions-c47ea85f2141 我建议您看一下: https : //medium.com/@sht_5/minimal-code-for-redux-async-actions-c47ea85f2141

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

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