反应挂钩搜索按钮点击不起作用

时间:2020-02-14 16:50:30

标签: javascript reactjs

我需要使用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始终为空。

如何使搜索工作正常?

1 个答案:

答案 0 :(得分:1)

尝试将nameSearch添加到依赖列表以进行useCallback:

v8

并确保setNameSearch实际上在const fetchData = useCallback(async () => { ... }, [license, nameSearch]); 内部使用,以便具有值。