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

如何在Reducer中递归添加Get请求获取的UserInfo对象?

Got it, let’s break down exactly how to implement this recursive object addition in your Redux reducer. I’ll walk you through each step with practical code examples that fit your requirement:

Step 1: Define Action Types & Creators

First, we need clear action types to trigger the recursive update, along with an action creator to pass the fetched UserInfo data:

// Action types (keep these consistent across your app)
export const ADD_USER_INFO_RECURSIVELY = 'ADD_USER_INFO_RECURSIVELY';

// Action creator to send the new UserInfo to the reducer
export const addUserInfoRecursively = (userInfo) => ({
  type: ADD_USER_INFO_RECURSIVELY,
  payload: userInfo
});
Step 2: Build a Recursive Helper Function

The core of this logic is a helper function that takes your current reducer state and the new UserInfo, then nests the new data recursively into the existing structure. For this example, we’ll build a deep nested chain (each new UserInfo becomes the child of the previous deepest node):

const nestUserInfo = (currentState, newUserInfo) => {
  // If state is empty, return the new UserInfo as the base
  if (!currentState) {
    return { ...newUserInfo };
  }

  // Check if the current node already has a nested child
  const hasNestedChild = Object.prototype.hasOwnProperty.call(currentState, 'nested');

  if (hasNestedChild && currentState.nested) {
    // Recursively traverse to the deepest node
    return {
      ...currentState,
      nested: nestUserInfo(currentState.nested, newUserInfo)
    };
  } else {
    // Attach the new UserInfo as the nested child of the current deepest node
    return {
      ...currentState,
      nested: { ...newUserInfo }
    };
  }
};

Note: If you need a different recursive structure (like a parent-child tree with specific IDs), just adjust the helper function’s condition for finding where to insert the new data.

Step 3: Implement the Reducer

Now wire up the helper function to your reducer. The reducer will handle the action and return the updated recursive state:

// Initial state can be null, empty object, or a base structure depending on your needs
const initialState = null;

const userInfoReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_USER_INFO_RECURSIVELY:
      // Use our helper to generate the new recursive state
      return nestUserInfo(state, action.payload);
    default:
      // Return the current state for unrecognized actions
      return state;
  }
};

export default userInfoReducer;
Step 4: Dispatch the Action After Successful API Request

Finally, in your API call logic, dispatch the action as soon as the Get request returns successful UserInfo data:

// Example using async/await with fetch (swap with axios if that's your tool)
const fetchAndAddUserInfo = () => async (dispatch) => {
  try {
    const response = await fetch('/your-api-endpoint/user-info'); // Replace with your actual API URL
    const userInfo = await response.json();

    // Dispatch the action to recursively add the new UserInfo to the reducer
    dispatch(addUserInfoRecursively(userInfo));
  } catch (error) {
    // Add your error handling logic here (e.g., dispatch an error action)
    console.error('Failed to fetch UserInfo:', error);
  }
};

This setup ensures every successful API request adds the new UserInfo to your reducer state in a recursive structure. You can tweak the helper function’s nesting logic to match whatever recursive pattern your app needs—whether it’s a deep chain, a tree with multiple children, or something else.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:03:26