javascript - 搜索查询不显示必要的数据
问题描述
我需要根据搜索查询从 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 不是一个函数。
解决方案
密钥和 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 ...
推荐阅读
- python-3.x - 如果特定元素已存在于上一个列表中,则不应重复创建具有特定元素的嵌套列表
- php - PHP未在查询中显示带有变量的MySQL结果
- python - Python3:如何将 set_description 与 tqdm.contrib.concurrent process_map 一起使用
- python - 如何修复 Django 中不存在订单匹配查询?
- swift - 错误:线程 1:异常:“此类与键标签的键值编码不兼容。”
- python - 如何在 Pysapar SQL 数据框中添加具有特定值的列?
- java - Cassandra QueryLogger 引入 NoHostAvailableException
- c - 是否有关于变量范围如何工作的任何解释
- vba - FileDialog 对象,可选择未过滤的文件类型
- java - 斯坦福 Java NLP 选区标签缩写