首页 > 解决方案 > 搜索查询不显示必要的数据

问题描述

我需要根据搜索查询从 API 中获取数据。输入要查找的电影名称后,按 Enter(提交表单),这些电影就会显示在屏幕上。但我的控制台抱怨。为什么。我尝试使用 axios 和端点 ${searchText} 来实现它

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

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

   const loadData = async () => {
    const res = await axios.get(url)
    setFilms(res.data.Search)
    console.log(res.data.Search)
   }

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

  return (
    <>
        <Container>
            <h1>Bookstore</h1>
            <Row>
            <form onSubmit={onSubmitHandler}>
            <input type='text'
                   placeholder='Search...'
                   name="searchText"
                   onChange={onTextChange}
                   value={searchText}
                 
            />
            
               </form>
            </Row>
            <Row>
              { films.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>
      
    </>
  );
}

它还抱怨films.map 不是一个函数。

标签: javascriptreactjsreact-hooks

解决方案


密钥和 url 更新

url 中的“YOUR_KEY”字符串应该是唯一的字符串(例如:RN33mfknds5josd),然后您可以使用搜索文本更新 url。

const baseUrl = "http://www.omdbapi.com/?apikey=YOUR_KEY" // todo: update the api key

function App() {
  const [films, setFilms] = useState([])
  const [searchText, setSearchText] = useState(baseUrl)

  useEffect (()=> { 
    loadData()
  }, [])

   const loadData = async () => {
    const res = await axios.get(url)
    setFilms(res.data.Search)
    console.log(res.data.Search)
   }

   const onTextChange = (e) => {
     if(e.target.value) {
       setSearchText(`${baseUrl}&s=${e.target.value}`)
     } else {
       setSearchText(baseUrl)
     }
   }
   const onSubmitHandler = (e) => {
     e.preventDafault()
     loadData()
  
  }

  return ...

推荐阅读