簡體   English   中英

如何使用 reactjs 從多個 API 獲取搜索結果

[英]How do I fetch search results from multiple API using reactjs

我是 ReactJS 的新手,我正在嘗試通過從多個 API 獲取數據來創建一個搜索功能。 下面是Search.js文件。 我嘗試了很多次以使其發揮作用並在打字時使結果實時顯示。 但是,我不斷收到此錯誤消息TypeError: values.map is not a function 我哪里出錯了,我該如何解決?

 function Search() { const [input, setInput] = useState(""); const [results, setResults] = useState([]); const urls = [ 'https://jsonplaceholder.typicode.com/posts/1/comments', 'https://jsonplaceholder.typicode.com/comments?postId=1' ] Promise.all(urls.map(url => fetch(url).then((values) => Promise.all(values.map(value => value.json()))).then((response) => response.json()).then((data) => setResults(data)).catch(error => console.log('There was a problem,', error)) ). []) const handleChange = (e) => { e;preventDefault(). setInput(e.target;value). } if (input.length > 0) { results.filter((i) => { return i.name.toLowerCase();match(input). }) } return ( < div className = "search" htmlFor = "search-input" > < input type = "text" name = "query" value = { input } id = "search" placeholder = "Search" onChange = { handleChange } /> { results,map((result. index) => { return ( < div className = "results" key = { index } > < h2 > { result.name } < /h2> < p > { result.body } < /p> { result } < /div> ) }) } </div> ) }
 .search { position: relative; left: 12.78%; right: 26.67%; top: 3%; bottom: 92.97%; }.search input { /* position: absolute; */ width: 40%; height: 43px; right: 384px; margin-top: 50px; top: 1.56%; bottom: 92.97%; background: rgba(0, 31, 51, 0.02); border: 1px solid black; border-radius: 50px; float: left; outline: none; font-family: 'Montserrat', sans-serif; font-style: normal; font-weight: normal; font-size: 16px; line-height: 20px; /* identical to box height */ display: flex; align-items: center; /* Dark */ color: #001F33; } /* Search Icon */ input#search { background-repeat: no-repeat; text-indent: 50px; background-size: 18px; background-position: 30px 15px; } input#search:focus { background-image: none; text-indent: 0px }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

問題

  1. 您從fetch(url)獲得的響應只是一個響應,因此 map 沒有任何內容。
  2. 數據獲取發生在組件的 function 主體中,因此在工作時會導致渲染循環,因為每個渲染周期都會獲取數據並更新 state。
  3. 在返回之前input.length > 0過濾什么都不做,因為返回的過濾數組沒有被保存,並且它也錯誤地搜索子字符串。
  4. 嘗試在渲染 function 中渲染result object,對象無效 JSX

解決方案

  1. 跳過.then((values) => Promise.all(values.map((value) => value.json())))步驟,然后繼續訪問 JSON 數據。
  2. 將數據獲取移動到掛載的useEffect掛鈎中,使其僅運行一次。
  3. 將過濾器 function 移動到渲染 function 中並使用 string.prototype.includes 進行搜索。
  4. 基於呈現的其他屬性以及result object 上剩下的內容,我假設您可能想要呈現email屬性。

代碼:

function Search() {
  const [input, setInput] = useState("");
  const [results, setResults] = useState([]);

  useEffect(() => {
    const urls = [
      "https://jsonplaceholder.typicode.com/posts/1/comments",
      "https://jsonplaceholder.typicode.com/comments?postId=1"
    ];

    Promise.all(
      urls.map((url) =>
        fetch(url)
          .then((response) => response.json())
          .then((data) => setResults(data))
          .catch((error) => console.log("There was a problem!", error))
      ),
      []
    );
  }, []);

  const handleChange = (e) => {
    e.preventDefault();
    setInput(e.target.value.toLowerCase());
  };

  return (
    <div className="search" htmlFor="search-input">
      <input
        type="text"
        name="query"
        value={input}
        id="search"
        placeholder="Search"
        onChange={handleChange}
      />
      {results
        .filter((i) => i.name.toLowerCase().includes(input))
        .map((result, index) => {
          return (
            <div className="results" key={index}>
              <h2>{result.name}</h2>
              <p>{result.body}</p>
              {result.email}
            </div>
          );
        })}
    </div>
  );
}

編輯 how-do-i-fetch-search-results-from-multiple-api-using-reactjs

暫無
暫無

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

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