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

React调用GitHub仓库搜索接口报repos.map is not a function错误如何解决

错误原因

你的输入框事件处理逻辑写错了:

  • 输入框内容变化时,你调用了setRepos(event.target.value),将原本初始化为数组的repos状态强制修改为了字符串类型,字符串原型上没有map方法,所以抛出了类型错误。
  • 输入框的内容应该绑定到name状态,你需要把inputChanged里的逻辑改为调用setName(event.target.value)。

修正后的完整代码

<script type="text/babel">
function GithubList() {
  const [repos, setRepos] = React.useState([]);
  const [name, setName] = React.useState('');

  const fetchRepo = () => {
    fetch(`https://api.github.com/search/repositories?q=${name}`)
      .then(response => response.json())
      .then(data => {
        // 增加类型判断,避免接口返回异常时报错
        if (Array.isArray(data.items)) {
          setRepos(data.items)
        } else {
          setRepos([])
        }
      })
      .catch(err => console.error(err))
  };

  const inputChanged = (event) => {
    // 修正:输入内容更新name状态,不是repos
    setName(event.target.value);
  };

  // 增加空值判断,避免repos非数组时报错
  const repoDetails = Array.isArray(repos) ? repos.map((repo,index) => (
    <tr key={index}>
      <td>{repo.full_name}</td>
      <td>{repo.url}</td>
    </tr>
  )) : [];

  return(
    <div>
      <h2>Repositories</h2>
      <input type="text" value={name} onChange={inputChanged} />
      <button onClick={fetchRepo}> Search </button>
      <table>
        <tbody>
          <tr>
            <th>Name</th>
            <th>URL</th>
          </tr>
          {repoDetails}
        </tbody>
      </table>
    </div>
  );
}
ReactDOM.render(<GithubList/>, document.getElementById("root"))
</script>

额外优化建议

  • 可以给搜索按钮加loading状态,避免用户重复点击触发多次请求
  • 可以给搜索输入框加防抖逻辑,也可以支持按回车直接触发搜索,不用手动点击按钮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:57:00