首页 > 解决方案 > 未捕获的类型错误:repos.map 不是函数

问题描述

我对使用 react 和 javascript 比较陌生,我正在尝试使用来自此存储库https://api.github.com/search/repositories?q=react的用户输入获取 api

map 应该是一个数组,但我似乎无法弄清楚为什么我的代码中出现此错误:

<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 => {
          setRepos(data.items)
        })
        .catch(err => console.error(err))
      };


      const inputChanged = (event) => {
        setRepos(event.target.value);
      };

      const repoDetails = 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>

标签: reactjs

解决方案


它应该是而setName不是setReposinputChanged

const inputChanged = (event) => {
  setName(event.target.value);
};

推荐阅读