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

React使用useReducer如何在页面加载时请求接口设置initialState初始用户数据

解决方法

你可以通过 useEffect 钩子在 GithubState 组件首次挂载时触发初始用户数据请求,直接复用现有 SEARCH_USERS 的 action 类型更新状态即可,无需修改现有 Reducer 逻辑。

具体修改步骤:

  • 在 GithubState 组件中导入 React 内置的 useEffect 钩子
  • 封装初始用户请求方法,调用 Github 公开的用户列表端点获取默认展示的用户
  • 配置空依赖的 useEffect,组件挂载完成后自动执行请求

修改后的 GithubState 完整代码:

import { useReducer, useEffect } from 'react';
import axios from 'axios';
import GithubReducer from './你的Reducer文件路径';
import { SEARCH_USERS, SET_LOADING } from '../types';

const GithubState = (props) => {
  const initialState = {
    users: [],
    user: {},
    repos: [],
    loading: false,
  };

  const [state, dispatch] = useReducer(GithubReducer, initialState);

  // 封装设置loading的方法(你原代码遗漏了这部分,补充完整)
  const setLoading = () => {
    dispatch({ type: SET_LOADING });
  };

  // 原有搜索用户方法
  const searchUsers = async (text) => {
    setLoading();
    const res = await axios.get(
      `https://api.github.com/search/users?q=${text}&client_id=${githubClientId}&client_secret=${githubClientaSecret}`
    );
    dispatch({
      type: SEARCH_USERS,
      payload: res.data.items,
    });
  };

  // 新增:获取初始默认用户列表
  const getInitialUsers = async () => {
    setLoading();
    // 调用github公开用户列表接口,可通过per_page参数调整初始加载的用户数量
    const res = await axios.get(
      `https://api.github.com/users?per_page=12&client_id=${githubClientId}&client_secret=${githubClientaSecret}`
    );
    dispatch({
      type: SEARCH_USERS,
      payload: res.data,
    });
  };

  // 新增:组件挂载时仅执行一次初始请求
  useEffect(() => {
    getInitialUsers();
  }, []);

  // 原有context provider逻辑保持不变,把新增方法按需传给子组件即可
  return (
    <GithubContext.Provider
      value={{
        users: state.users,
        user: state.user,
        repos: state.repos,
        loading: state.loading,
        searchUsers,
      }}
    >
      {props.children}
    </GithubContext.Provider>
  );
};

export default GithubState;

补充说明

  • 无需修改现有 Reducer 代码,已有的 SEARCH_USERS 逻辑完全兼容初始数据更新需求
  • 用户触发搜索操作后,返回的搜索结果会自动覆盖初始用户列表,不会产生逻辑冲突
  • Github公开用户接口默认返回30条数据,可通过修改per_page参数自定义初始加载数量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:54:03