You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS技术术语解析:Reducer相关术语及Middleware、Thunk、Redux-logger说明

React Reducer 相关术语及核心工具解析

Hey there! Let's break down all the key terms tied to reducers in React (specifically Redux, since reducers are core to Redux's architecture), plus explain the middleware tools you'll likely use in your day-to-day projects.


Reducer 相关核心术语

1. Reducer 函数

The star of the show! A reducer is a pure function that takes two arguments: the current state of your application (or a slice of it) and an action. It returns a brand new state object (never mutate the original state!) based on the action's type. The golden rule: same input always gives the same output—no side effects allowed here.

2. Action

An action is a plain JavaScript object that describes what happened in your app. It must have a type field (usually a string like 'ADD_TODO' or 'FETCH_DATA_SUCCESS') to tell the reducer how to update the state. You can also include a payload field to pass along data needed for the state update (e.g., a new todo item or fetched API data). Example:

{
  type: 'ADD_TODO',
  payload: 'Pick up groceries'
}

3. Dispatch

Dispatch is a method provided by the Redux store that sends actions to the reducer. When you call dispatch(action), the store passes that action to your reducer, which then updates the state accordingly. It's the bridge between your components and the state management logic.

4. Store

The store is the single source of truth for your app's state in Redux. It holds the entire state tree, and you create it using createStore() (or configureStore() in Redux Toolkit). The store gives you access to:

  • getState(): Get the current state
  • dispatch(): Send actions to the reducer
  • subscribe(): Listen for state changes

5. Pure Function

A critical requirement for reducers. A pure function has no side effects (no API calls, no modifying global variables, no random values), and it always returns the same output for the same input. This predictability is what makes Redux state changes easy to debug and track.


Middleware, Thunk, and Redux-logger: Concepts & Roles

1. Middleware (Redux Middleware)

Think of middleware as a "middle layer" that sits between when you dispatch an action and when that action reaches the reducer. It lets you extend Redux's functionality by adding custom logic—like handling async operations, logging, or even modifying actions before they hit the reducer. Middleware wraps the dispatch function, so you can intercept actions and run code at that stage.

2. Redux-thunk

Redux-thunk is the most popular middleware for handling async logic in Redux. By default, Redux only lets you dispatch plain action objects. Thunk changes that: it allows you to dispatch functions (called "thunks") instead. These functions can contain async code (like API calls), and once the async operation completes, they dispatch the actual plain action to the reducer.

Here's a quick example of a thunk action:

const fetchUser = (userId) => {
  // Return a function that gets access to dispatch
  return (dispatch) => {
    dispatch({ type: 'FETCH_USER_START' });
    // Async API call
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(userData => {
        dispatch({ type: 'FETCH_USER_SUCCESS', payload: userData });
      })
      .catch(error => {
        dispatch({ type: 'FETCH_USER_FAILURE', payload: error.message });
      });
  };
};

// Dispatch the thunk from your component
dispatch(fetchUser(123));

Thunk's superpower is letting you manage async workflows (like loading states, success/failure handling) directly in your action logic, keeping your reducers clean and focused on state updates.

3. Redux-logger

Redux-logger is a debugging middleware that logs every action dispatched, along with the previous state and the new state after the reducer runs. It's incredibly useful for tracking how your state changes over time—you can see exactly what action was triggered, what data it carried, and how it affected the state.

When you add redux-logger to your store, you'll see output like this in your browser's console:

action FETCH_USER_SUCCESS @ 14:22:15
prev state: { user: null, loading: true, error: null }
action: { type: 'FETCH_USER_SUCCESS', payload: { id: 123, name: 'Jane Doe' } }
next state: { user: { id: 123, name: 'Jane Doe' }, loading: false, error: null }

It's a must-have for debugging Redux apps, especially when you're trying to track down unexpected state changes.


内容的提问来源于stack exchange,提问作者lex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:24:25