简体   繁体   English

React.js:为什么搜索过滤器不起作用?

[英]React.js: why search filter doesn't work?

I am trying to make work search input .我正在尝试进行工作搜索输入 I'm filtering through fetched data in useEffect in Hooks/useCountries component, listening to input in App.js and passing props for handleChange in Searchbar component.我过滤通过钩/ useCountries分量useEffect取出的数据,听输入App.js和通过道具handleChange搜索栏组件。 Something is missing, I can't figure out what.有些东西不见了,我无法弄清楚是什么。
Here is the link of codesandbox and Hooks/useCountries component这是codeandboxHooks/useCountries组件的链接

import React, { useState, useEffect } from "react";

export default function useCountries(search) {
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);

  const fetchData = () => {
    fetch("https://restcountries.eu/rest/v2/all")
      .then((res) => res.json())
      .then((result) => setData(result))
      .catch((err) => console.log("error"));
  };
  useEffect(() => {
    const searchResult =
      data &&
      data
        .filter((item) => item.name.toLowerCase().includes(search))
        .map((element) => <div>{element.name}</div>);
  }, []);

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

  return [data, error];
}


App.js应用程序.js


import React, { useState } from "react";

import SearchBar from "./components/SearchBar";
import useCountries from "./Hooks/useCountries";
import MainTable from "./components/MainTable";

import "./App.scss";

export default function App() {
  const [search, setSearch] = useState("");
  const [data, error] = useCountries(search);

  const handleChange = (e) => {
    setSearch(e.target.value);
  };

  return (
    <div className="App">
      <SearchBar handleChange={handleChange} search={search} />
      <MainTable countries={data} />
    </div>
  );
}


SearchBar component搜索栏组件

import React, { useState } from "react";

import "./SearchBar.scss";

export default function Searchbar({ handleChange, search }) {
  return (
    <div className="SearchBar">
      <input
        className="input"
        type="text"
        placeholder="search country ..."
        value={search}
        onChange={handleChange}
      />
    </div>
  );
}


So in your useCountries hook, you need to update the useEffect to trigger whenever search is changed.因此,在您的useCountries挂钩中,您需要更新 useEffect 以在搜索更改时触发。 Otherwise, it runs when the hook is first loaded, but then never again.否则,它会在钩子第一次加载时运行,但以后再也不会运行。 I'm also not exactly sure what your logic is attempting to accomplish in your current useEffect .我也不确定您的逻辑试图在您当前的useEffect完成useEffect I've posted a possible update to it that also changes your search to regex to account for the possibility that the user may not be typing in lower case.我已经发布了一个可能的更新,它也将您的搜索更改为正则表达式,以解决用户可能没有输入小写字母的可能性。 Let me know if this doesn't work for your use case and I can adapt it.如果这不适用于您的用例,请告诉我,我可以对其进行调整。

import React, { useState, useEffect } from "react";

export default function useCountries(search) {
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);
  const [searchResults, setSearchResults] = useState(null);
  const fetchData = () => {
    fetch("https://restcountries.eu/rest/v2/all")
      .then((res) => res.json())
      .then((result) => setData(result))
      .catch((err) => console.log("error"));
  };
  useEffect(() => {
    if (search) {
      const searchCriteria = new RegExp(search, "i");
      setSearchResults(
        data
          .filter((item) => searchCriteria.test(item.name))
          .map((element) => <div>{element.name}</div>)
      );
    } else {
      setSearchResults(null);
    }
  }, [search]);

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

  return [data, error, searchResults];
}

And in App.js add:在 App.js 中添加:

const [data, error, searchResults] = useCountries(search);

Here is the fork off of your sandbox where this works: CodeSandbox这是您的沙箱的分支,它可以工作: CodeSandbox

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM