【发布时间】:2021-12-20 17:32:02
【问题描述】:
我目前正在通过从 useEffect 挂钩中的 API 获取来呈现一些数据。
我有一个searchValue 变量,它保存用户在主页搜索字段中输入的值。这被传递给这个component。
我在useEffect 依赖项中设置了searchValue,这样当它发生变化时,它会再次运行效果。
当它挂载时,它似乎正在跳过!res.ok if 语句。我已将res.ok 记录到此 if 语句之外的控制台,并且每个字符输入到searchValue 中,它总是返回true。按下字符后响应状态始终为 200,因此它永远不会运行 !res.ok if 语句块。我对生命周期或异步调用的理解一定有问题。
我收到错误:countriesData.map is not a function - 所以它试图在无效数据上渲染map,但这甚至不应该返回,因为我首先在Content 函数中写入了if (error)。如果匹配,则应返回错误消息,但会跳过此消息,并使用无效数据更新 countriesData。我的代码如下,请帮忙!我觉得我遗漏了一些简单的东西并且误解了 React 的一些基础知识!
import { useEffect, useState } from 'react'
import CountryCard from '../CountryCard'
import { countries } from './CountriesList.module.css'
const CountriesList = ({ searchValue }) => {
const [error, setError] = useState(false)
const [loading, setLoading] = useState(true)
const [countriesData, setCountriesData] = useState([])
useEffect(() => {
const getCountries = async () => {
let res = await fetch('https://restcountries.com/v2/all')
if (searchValue !== '') {
res = await fetch(
`https://restcountries.com/v2/name/${searchValue}`
)
}
if (!res.ok) {
console.log(res)
return setError(true)
}
const data = await res.json()
setCountriesData(data)
setLoading(false)
}
getCountries()
// return () => setLoading(true)
}, [searchValue])
const Content = () => {
if (error) {
return <div>Error: please check the country you have typed</div>
}
if (loading) {
return <div>Loading...</div>
}
return (
<section className={`${countries} columns is-multiline`}>
{countriesData.map((country) => (
<CountryCard {...country} key={country.name} />
))}
</section>
)
}
return <Content />
}
export default CountriesList
【问题讨论】:
标签: javascript reactjs async-await fetch react-lifecycle