【问题标题】:How to implement fetch API by search如何通过搜索实现 fetch API
【发布时间】:2020-12-03 00:17:23
【问题描述】:

我有一个搜索栏。当我输入任何电影的名称时,必须显示过滤后的数据(作为从 API 获取的结果)

function App() {
  const [films, setFilms] = useState([])
  const [searchText, setSearchText] = useState('')
  const [filteredRes, setFilteredRes] = useState([])

  const url = `http://www.omdbapi.com/?apikey=KEY&s=${searchText}`
  useEffect (()=> { 
    loadData()
  }, [searchText])

   const loadData = async () => {
    const res = await axios.get(url)
   
    setFilms(res.data.Search)
    const filtered = await films.filter(i => i.toLowerCase().includes(searchText))
    setFilteredRes(filtered)

   }

   const onTextChange = (e) => {
     setSearchText(e.target.value)
   }
   

  return (
    <>
        <Container>
            <h1>Bookstore</h1>
            <Row>
            <form>
            <input type='text'
                   placeholder='Search...'
                   name="searchText"
                   onChange={onTextChange}
                   value={searchText}
                 
            />
           
               </form>
            </Row>
            <Row>
              { filteredRes.map(item => {
                return ( 
                
                  <Col lg={3} md={3} sm={12} key={item.imdbID}>
                   <img src={item.poster}/> 
                   <h6>{item.title}</h6>
                   <h6>{item.year}</h6>
                  </Col>

                )
              })}
        
            </Row>
        </Container>
      
    </>
  );
}

我有问题: 未处理的拒绝(TypeError):无法读取未定义的属性“过滤器”。但是,如果我将获取的电影保存在 const [films] 中,为什么?

【问题讨论】:

    标签: reactjs api react-redux react-hooks


    【解决方案1】:

    输出:

    您不必额外过滤获取的数据,Axios 正在获取的数据已经根据serchText 进行过滤,因此 Axios 调用完成了所有操作。

    完整示例:

    import React, { useState } from "react";
    import Axios from "axios";
    
    const APIKEY = "your api";
    export default function App() {
      const [searchText, setSearchText] = useState("");
      const [films, setFilms] = useState([]);
    
      const handleSubmit = (event) => {
        event.preventDefault();
        if (!searchText) {
          alert("Please enter movie name");
          return;
        }
        Axios.get(
          `http://www.omdbapi.com/?i=tt3896198&apikey=${APIKEY}&s=${searchText}`
        )
          .then((response) => {
            console.log(response.data);
            setFilms(response.data.Search);
          })
          .catch((error) => {
            console.log(error);
          });
      };
      return (
        <div className="App">
          <form onSubmit={handleSubmit}>
            <input
              placeholder={"Search movie"}
              onChange={(event) => {
                setSearchText(event.target.value);
              }}
            />
            <button>Search</button>
          </form>
    
          {films.map((film) => (
            <div>
              <img src={film["Poster"]} alt={film["Title"]} width={100} />
              <p>{film["Title"]}</p>
              <p>{film["Year"]}</p>
            </div>
          ))}
        </div>
      );
    }
    
    

    Github Repo

    【讨论】:

    • 好的。谢谢你。但我还有另一个问题。我获取(查找)的数据在控制台中返回一个空数组。
    • 但是当我插入你的url地址时,控制台显示401状态码,据说我是未经授权的
    • 另外,不要在代码沙箱或其他在线编辑器上运行它,当我尝试从 Codesandbox 和 Stackblitz 运行此应用程序时遇到网络错误,所以我在本地机器,它运行良好。
    • 使用条件渲染然后{films?.map((film) =&gt; ( &lt;div&gt; &lt;img src={film["Poster"]} alt={film["Title"]} width={100} /&gt; &lt;p&gt;{film["Title"]}&lt;/p&gt; &lt;p&gt;{film["Year"]}&lt;/p&gt; &lt;/div&gt; ))}
    • 已修复,现在可以使用了!谢谢你的月亮和回来:)
    猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多