Hiểu về Redux Thunk và Hành động Không đồng bộ trong Redux

Hiểu về Redux Thunk và Hành động Không đồng bộ trong Redux

Tìm hiểu về Redux Thunk, một middleware mạnh mẽ cho Redux, giúp đơn giản hóa việc xử lý các hành động không đồng bộ trong ứng dụng Redux của bạn.
02/03/2024
9,927 Lượt xem

Giới thiệu về Redux Thunk

Redux Thunk là một middleware cho Redux, cho phép bạn viết các hành động trả về một hàm thay vì một đối tượng hành động đơn giản. Điều này giúp bạn giải quyết một số vấn đề phổ biến trong các ứng dụng Redux:

  • Xử lý các tác vụ không đồng bộ, chẳng hạn như gọi API hoặc tương tác với cơ sở dữ liệu.
  • Trì hoãn gửi một hành động hoặc điều chỉnh hành động dựa trên một điều kiện nhất định.
  • Chia các hành động phức tạp thành nhiều hành động nhỏ hơn.

Với Redux Thunk, thay vì trả về một đối tượng hành động đơn giản, bạn có thể trả về một hàm. Hàm này sẽ nhận được phương thức `dispatch` của Redux và có thể sử dụng nó để gửi nhiều hành động không đồng bộ dựa trên các điều kiện khác nhau.

Cài đặt Redux Thunk

Để sử dụng Redux Thunk, bạn cần cài đặt nó như một phụ thuộc trong dự án của mình:

npm install redux-thunk

Sau đó, bạn cần áp dụng Redux Thunk như một middleware trong cấu hình Redux của bạn:

javascript Copy code import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers'; const store = createStore(rootReducer, applyMiddleware(thunk));

Sử dụng Redux Thunk

Với Redux Thunk được cài đặt và áp dụng, bạn có thể bắt đầu sử dụng nó để tạo các hành động không đồng bộ. Thay vì trả về một đối tượng hành động đơn giản, bạn có thể trả về một hàm từ hành động của bạn.

Ví dụ về hành động không đồng bộ với Redux Thunk

Giả sử bạn có một ứng dụng ghi chú Todo và muốn tải danh sách công việc từ một API khi ứng dụng khởi chạy. Bạn có thể tạo một hành động không đồng bộ để thực hiện điều này bằng cách sử dụng Redux Thunk:

javascript Copy code import axios from 'axios'; const fetchTodos = () => { return (dispatch) => { axios.get('/api/todos') .then((response) => { dispatch({ type: 'FETCH_TODOS_SUCCESS', payload: response.data }); }) .catch((error) => { dispatch({ type: 'FETCH_TODOS_ERROR', payload: error }); }); } };

Trong ví dụ này, hành động `fetchTodos` trả về một hàm thay vì một đối tượng hành động đơn giản. Hàm này nhận phương thức `dispatch` làm đối số và sử dụng nó để gửi các hành động khác dựa trên kết quả của cuộc gọi API.

Bạn có thể gọi hành động này trong thành phần React của mình bằng cách sử dụng `mapDispatchToProps` hoặc hook `useDispatch`:

javascript Copy code import { useDispatch } from 'react-redux'; import { fetchTodos } from './actions'; const TodoList = () => { const dispatch = useDispatch(); useEffect(() => { dispatch(fetchTodos()); }, [dispatch]); // Hiển thị danh sách Todo // ... };

Lợi ích của Redux Thunk

Redux Thunk mang lại nhiều lợi ích cho việc xử lý các hành động không đồng bộ trong Redux:

Đơn giản hóa mã nguồn

Thay vì viết các hàm thunk, trình xử lý hành động và middleware phức tạp để xử lý các hành động không đồng bộ, Redux Thunk cho phép bạn viết mã nguồn đơn giản hơn bằng cách sử dụng các hàm trả về hành động thay vì đối tượng hành động.

Tách biệt mã nguồn

Bằng cách sử dụng Redux Thunk, bạn có thể tách biệt mã nguồn xử lý hành động không đồng bộ ra khỏi thành phần React của bạn, giúp duy trì tính nhất quán và có thể bảo trì tốt hơn.

Dễ dàng xử lý các trường hợp phức tạp

Redux Thunk cung cấp một cách linh hoạt để xử lý các trường hợp không đồng bộ phức tạp, chẳng hạn như khi bạn cần gửi nhiều hành động dựa trên điều kiện nhất định hoặc kết quả của một tác vụ không đồng bộ.

Kết luận

Redux Thunk là một middleware mạnh mẽ và hữu ích cho phép bạn xử lý các hành động không đồng bộ trong Redux một cách đơn giản hơn. Bằng cách sử dụng hàm trả về hành động thay vì đối tượng hành động đơn giản, bạn có thể tách biệt mã nguồn, đơn giản hóa việc xử lý các trường hợp phức tạp và cuối cùng là viết mã nguồn dễ bảo trì hơn. Nếu bạn đang phát triển ứng dụng Redux có liên quan đến các tác vụ không đồng bộ, hãy xem xét sử dụng Redux Thunk để tận dụng tối đa các lợi ích của nó.

Các bạn có thể tham khảo thêm nguồn khác:

Writing Logic with Thunks | Redux

In a sense, a thunk is a loophole where you can write any code that needs to interact with the Redux store, ahead of time, without needing to know which Redux store will be used. This keeps the logic>

Thunks in Redux: The Basics - Medium

The redux-thunkmiddleware, once installed, does essentially the following: If a normal action object is dispatched, redux-thunksimply passes it along (e.g. into the reducer), as if...>

Redux Thunk Explained with Examples - freeCodeCamp.org

Redux Thunk is middleware that allows you to return functions, rather than just actions, within Redux. This allows for delayed actions, including working with promises. One of the main use cases for t>

Redux Thunk - Javatpoint

What is Redux Thunk? Thunk is a logical concept in programming where you deal with a function that is primarily used to delay the calculation or evaluation of any operation. Redux Thunk acts as a midd>

GitHub - reduxjs/redux-thunk: Thunk middleware for Redux

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condi>

What is the use of middleware Redux thunk - GeeksforGeeks

Step 1: To set up redux with thunk, we will start by creating a react application, and install all the required dependencies. Run the following command to create a new react application. npx create-re>

Why use Redux Thunk? - Medium

Redux Thunk is a popular middleware for… | by Istvan Keri | Medium 500 Apologies, but something went wrong on our end. Refresh the page, check Medium 's site status, or find something interesting...>

Redux Thunk explicado con ejemplos - freecodecamp.org

Redux Thunk es un middleware que nos permite retornar funciones, en lugar de solo acciones en Redux. Esto nos permite trabajar con acciones retrasadas y promesas. Uno de los principales casos de uso p>

reactjs - What's wrong with my Redux Thunk? It's being called alright ...

I'm new to this and read many tutorial and docs about Redux Thunk and Higher Order Components. I am trying to wire this together but I can't understand what's wrong here. This image show what's happen>

redux-thunk入门 - 简书

redux-thunk就是redux的中间件,中间件就是你可以在收到请求和返回请求之间做一些操作。 而thunk中文意思是形实转换程序, 这样可能不太好理解我们来看例子。 let x = 1 + 2; let foo = () => 1 + 2; 这是官方给出来的例子,我们可以大致理解为当一个操作被delay的时候我们可以称之为thunk。 A thunk is a function that r>

Redux Thunk · React Redux Firebase

redux-thunk Integration getFirebase As Extra Argument. In order to get the most out of writing your thunks, make sure to set up your thunk middleware using its redux-thunk's withExtraArgument method l>

Understanding Asynchronous Redux Actions with Redux Thunk

Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store's dispatch method, which is then used to dispatch re>

What redux-thunk offer for async call? - Stack Overflow

Confusing is what redux-thunk offers with the async call when both snippets (one using redux-thunk and one without it) produce exact same output (not overall difference but with the above scenario). I>

Understanding Redux Thunk. Redux is a state management library… | by ...

What Redux Thunk really is. Now the returning function can accept two parameters. Those are dispatch and getState.This is great because with dispatch we can call other action creators. So now all we d>

GitHub - ShahariarRahman/react-redux-thunk-practice

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior.>

createAsyncThunk | Redux Toolkit - js

createAsyncThunk Overview . A function that accepts a Redux action type string and a callback function that should return a promise. It generates promise lifecycle action types based on the action typ>

Why do you need Redux Thunk? - TimesMojo

Redux Thunk is a Thunk middleware for Redux. It allows you to write asynchronous logic that interacts with the store. This awesome middleware allows you to write action creators that return a function>

Tìm hiểu về Redux Thunk

Redux Thunk được sử dụng để xử lý các logic bất đồng bộ phức tạp cần truy cập đến Store hoặc đơn giản là việc lấy dữ liệu như Ajax request. Đến đây có lẽ các bạn đã hiểu được mục đích của Redux Thunk>

redux-thunk入門、簡単まとめ - Qiita

で、React / Redux はどういう風にThunkの仕組みを利用しているのかというと、主には actions 、 action creators 、 components が「直接的に」データに (Asyncなどによる)影響を起こさせないようにしています。 それらの処理は全部Thunkに包んで、そのあとmiddlewareがThunk呼ぶ時に実行されます。 このようの仕組みだと、少なくともM>

Redux-Saga vs. Redux-Thunk: Key Differences With Examples

Innovative Mobility Solutions for Startups and Enterprises. Web App Development Design & Development of high performance web applications. Healthcare Cloud Services Lower IT cost and improve efficienc>

Redux Fundamentals, Part 6: Async Logic and Data Fetching

The Redux thunk middleware is available on NPM as a package called redux-thunk. We need to install that package to use it in our app: npm install redux-thunk Once it's installed, we can update the Red>

Easiest Way to Learn Redux Thunk with Example - Logistic Infotech

Redux-thunk is not alternate of Redux, but it extends Redux functionality and works as middleware by which we can keep our reducer code clean from API calls and once we get API response we can easily>

Redux Thunk: How To Use Redux Thunk In React - AppDividend

Redux Thunk is the middleware that calls the action creators that return a function instead of the action object. That function then receives the store's dispatch method, which is then used to dispatc>

Redux Thunk vs Redux Saga - InfoBeans CloudTech Limited - Eternus Solutions

Choosing one is difficult as both have its advantages and disadvantages. Redux-Thunk. Redux-Saga. Less boilerplate code. More boilerplate code. Easy to understand as compared to redux-saga. Difficult>

Understanding Redux and Thunk. I am at the end of my Flatiron School ...

Thunk works in conjunction with Redux, handling asynchronous calls, incorporating async code in the Redux action creator. It allows us to return a function inside of our action creator. That function>

Redux Thunkを使用した非同期Reduxアクションを理解する | DigitalOcean

Redux Thunkは、アクションオブジェクトの代わりに関数を返すアクションクリエーターを呼び出すことができるミドルウェアです。 この関数はストアのディスパッチメソッドを受け取り、非同期操作が完了すると、関数本体内で通常の同期アクションをディスパッチするために使用されます。 この記事では、Redux Thunkを追加する方法と、仮のTodoアプリケーションにどのように適合するかを学びます。 前提>

Redux Thunk Middleware In Redux-Toolkit with async await

So, we'll learn how to use redux-thunk with an example. We'll make the get request, fetch the data, and display the data using async await. So first create the react-app. npx create-react-app redux-th>

Redux Thunk download | SourceForge.net

Redux Thunk is Thunk middleware for Redux. With basic Redux, only simple synchronous updates can be done by dispatching an action. By adding middleware, you extend the Redux store's abilities, enablin>

Get started with Redux Thunk | Creative Bloq

Redux Thunk is a middleware - functionality that sits between actions and reducers that can change how those actions behave. Redux supports multiple sets of middleware that cover the entire applicatio>


Tags:
SHARED HOSTING
70% OFF
$2.99/mo $0.90/mo
SHOP NOW
RESELLER HOSTING
25% OFF
$12.99/mo $9.74/mo
SHOP NOW