簡體   English   中英

需要幫助使用 react v17 過濾自動完成數組

[英]Need help filtering an autocomplete array with react v17

我在這個主題上找到的大多數教程都已經過時了。 所以我來了。 我希望用這個應用程序做的是,在字段中輸入文本並根據您輸入的內容過濾結果。 目前我被困住了,我已經使用了很多數組方法,例如 filter、indexOf 等。我確定我對這個問題想得太多了,所以我需要幫助。 這是我目前擁有的代碼:

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

const ITEMS_API_URL = "https://restcountries.eu/rest/v2/all";

function Autocomplete() {
  const [countryArr, setCountryArr] = useState([]);
  useEffect(() => {
    axios.get(ITEMS_API_URL).then((res) => {
      setCountryArr(() => {
        let arr = res.data;
        arr.splice(10, arr.length);
        return arr;
      });
      console.log(countryArr);
    });
  }, []);


  const onChange = e => {
    const inputValue = e.target.value
    const filteredSuggestions = countryArr.find(arr => arr.name == inputValue)
    setCountryArr(filteredSuggestions)

    
  }
  return (
    <div className="wrapper">
      <div className="control">
        <input type="text" className="input" onChange={onChange} />
      </div>
      <div className="list is-hoverable" />
        {countryArr.map((country) => {
          return (
            <ul key={country.numericCode}>
              {country.name}
            </ul>

          )
        })}
    </div>
  );
}


export default Autocomplete;

您不應更改為實際數據源 ( countryArr ),否則它會重置並存儲最后過濾的數據源。 所以我為過濾器創建了狀態變量filteredCountryArr ,並在其上設置了過濾值。

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

const ITEMS_API_URL = "https://restcountries.eu/rest/v2/all";

function Autocomplete() {
  const [countryArr, setCountryArr] = useState([]);
  const [filteredCountryArr, setFilteredCountryArr] = useState([]);
  useEffect(() => {
    axios.get(ITEMS_API_URL).then(res => {
      setCountryArr(() => {
        let arr = res.data;
        arr.splice(10, arr.length);
        return arr;
      });
      console.log(countryArr);
    });
  }, []);

  const onChange = e => {
    const inputValue = e.target.value;
    const filteredSuggestions = countryArr.find(arr => arr.name == inputValue);
    setFilteredCountryArr(filteredSuggestions);
  };
  return (
    <div className="wrapper">
      <div className="control">
        <input type="text" className="input" onChange={onChange} />
      </div>
      <div className="list is-hoverable" />
      {filteredCountryArr && filteredCountryArr.length > 0  && filteredCountryArr.map(country => {
        return <ul key={country.numericCode}>{country.name}</ul>;
      })}
    </div>
  );
}

export default Autocomplete;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM