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

React搜索功能问题:API调用中searchTerm无法正确传递求助

问题排查与修复

核心问题及解决方法

  • 模板字符串语法错误:你使用单引号(')包裹API地址,导致${searchTerm}被当作字面量字符串传递,而非变量值。模板字符串必须用反引号("`")包裹才能解析变量。
  • 未返回JSON响应:第一个.then()中调用了res.json()但未返回结果,导致后续.then()无法获取解析后的数据,setSuggestions会接收到undefined。
  • API响应结构适配:dummyjson的搜索接口返回的是包含users数组的对象,直接传递data会导致状态存储整个响应对象,而非用户列表。

修正后的代码

useEffect(() => {
    const fetchUsers = () => {
      if (searchTerm.trim() === '') {
        setSuggestions([]);
        return;
      }
      // 用反引号包裹模板字符串解析变量
      fetch(`https://dummyjson.com/users/search?q=${searchTerm}`)
        .then((res) => {
          // 返回解析后的JSON数据
          return res.json();
        })
        .then((data) => {
          // 提取响应中的users数组更新状态
          setSuggestions(data.users);
        })
        .catch((err) => {
          console.log('error', err);
        });
    };
    fetchUsers();
  }, [searchTerm]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 20:21:00