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

React项目中如何存储GitHub API搜索的用户搜索记录?

选择localStorage还是React useContext?

先明确核心需求

先搞清楚你要的是「临时跨页面共享」还是「持久化保存搜索记录」,这是选方案的关键:

1. 用React useContext的情况

  • 适用场景:仅需要在当前会话内(页面不刷新、浏览器不关闭)让多页面共享搜索内容,不需要刷新后保留数据。
  • 优点:
    • 属于React内部状态管理,和组件生命周期同步,无需手动处理序列化/反序列化。
    • 状态更新会自动触发组件重渲染,保证页面数据实时同步。
  • 实现示例:
    // 创建搜索历史Context
    const SearchHistoryContext = React.createContext<{
      searchHistory: string[];
      addSearch: (text: string) => void;
    }>({
      searchHistory: [],
      addSearch: () => {}
    });
    
    // 提供Context的Provider组件
    export function SearchHistoryProvider({ children }: { children: React.ReactNode }) {
      const [searchHistory, setSearchHistory] = React.useState<string[]>([]);
    
      const addSearch = (text: string) => {
        // 避免重复添加相同搜索内容
        if (!searchHistory.includes(text)) {
          setSearchHistory(prev => [...prev, text]);
        }
      };
    
      return (
        <SearchHistoryContext.Provider value={{ searchHistory, addSearch }}>
          {children}
        </SearchHistoryContext.Provider>
      );
    }
    
    // 在搜索页面的handleSubmit中调用
    const { addSearch } = React.useContext(SearchHistoryContext);
    const handleSubmit = (e: React.MouseEvent<HTMLElement>) => {
      e.preventDefault();
      axios
        .get(`https://api.github.com/users/${inputText}/repos`)
        .then((response) => {
          setData(response.data);
          addSearch(inputText); // 将搜索内容加入历史
        })
        .catch((error) => {
          console.log('error', error);
        });
    };
    
    // 在目标页面获取搜索历史
    const { searchHistory } = React.useContext(SearchHistoryContext);
    

2. 用localStorage的情况

  • 适用场景:需要持久化保存搜索记录,比如用户关闭浏览器再打开,之前的搜索内容仍能查看。
  • 注意点:
    • localStorage仅支持存储字符串,需要用JSON.stringify序列化数组,读取时用JSON.parse反序列化。
    • 手动操作localStorage不会触发React组件重渲染,若要实时同步,建议结合useState或useContext使用。
  • 实现示例:
    // 搜索页面的handleSubmit
    const handleSubmit = (e: React.MouseEvent<HTMLElement>) => {
      e.preventDefault();
      axios
        .get(`https://api.github.com/users/${inputText}/repos`)
        .then((response) => {
          setData(response.data);
          // 保存到localStorage
          const existingHistory = JSON.parse(localStorage.getItem('searchHistory') || '[]');
          if (!existingHistory.includes(inputText)) {
            existingHistory.push(inputText);
            localStorage.setItem('searchHistory', JSON.stringify(existingHistory));
          }
        })
        .catch((error) => {
          console.log('error', error);
        });
    };
    
    // 目标页面读取并展示数据
    const [searchHistory, setSearchHistory] = React.useState<string[]>([]);
    React.useEffect(() => {
      const savedHistory = JSON.parse(localStorage.getItem('searchHistory') || '[]');
      setSearchHistory(savedHistory);
    }, []);
    

总结建议

  • 无需持久化,仅当前会话跨页共享:优先用React useContext,状态管理更贴合React组件逻辑,同步更顺畅。
  • 需要持久化保存搜索记录:用localStorage + useState/useContext结合,既保证数据持久,又能让组件实时响应数据变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:40:54