我需要使用GitHub API获取存储库列表,搜索必须在单击按钮和更改带有许可证的selectBox上进行

import React, { useState, useEffect, useCallback } from "react";
import axios from "axios";
import moment from "moment";
import { Layout } from "./../Layout";
import { List } from "./../List";
import { Loader } from "./../Loader";
import { Header } from "./../Header";
import { Search } from "./../Search";
import { Licenses } from "./../Licenses";

import "./App.css";

export const App = () => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState(false);
  const [nameSearch, setNameSearch] = useState("");
  const [license, setLicense] = useState({});

  const fetchData = useCallback(async () => {
    setHasError(false);
    setIsLoading(true);

    try {
      const prevMonth = moment()
        .subtract(30, "days")
        .format("YYYY-MM-DD");

      const licenseKey = (license && license.key) || "";

      const response = await axios(
        `https://api.github.com/search/repositories?q=${nameSearch}+in:name+language:javascript+created:${prevMonth}${
          licenseKey ? `+license:${licenseKey}` : ""
        }&sort=stars&order=desc`
      );
      setData(response.data.items);
    } catch (error) {
      setHasError(true);
      setData([]);
    }
    setIsLoading(false);
  }, [license]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return (
    <Layout>
      <Header>
        <Search
          handleSearchChange={setNameSearch}
          nameSearch={nameSearch}
          isLoading={isLoading}
          onSearch={fetchData}
        />
        <Licenses license={license} handleLicenseChange={setLicense} />
      </Header>

      <main>
        {hasError && <div>Error</div>}

        {isLoading ? <Loader /> : <List data={data} />}
      </main>
    </Layout>
  );
};


首先,我得到警告
带有警告编译。
./src/components/App/App.js
  第42:6行:React Hook useCallback缺少依赖项:'nameSearch'。包括它或删除依赖项数组react-hooks / exhaustive-deps

而且我的搜索无法正常工作,因为nameSearch在查询字符串中始终为空。

如何使搜索工作?

最佳答案

尝试将nameSearch添加到useCallback的依赖项列表中:

const fetchData = useCallback(async () => {
  ...
}, [license, nameSearch]);


并确保在Search.js中实际使用了setNameSearch,以便它具有一个值。

10-06 04:20