【发布时间】:2020-11-03 23:20:15
【问题描述】:
下面的useEffect 钩子应该设置weather 变量,但它没有这样做——相反,React 组件在调用钩子之前返回。
为什么在 React 组件返回之前没有调用 useEffect 钩子,我该如何解决这个问题?
// A React component that shows a given city's weather.
const CityWeather = ({ city }) => {
const [weather, setWeather] = useState({})
useEffect(() => {
axios
.get(`http://api.weatherapi.com/v1/current.json` +
`?key=${process.env.REACT_APP_MY_SUPER_SECRET_WEATHER_API_KEY}` +
`&q=${city}`)
.then(response => {
console.log(`response is ${JSON.stringify(response)}`)
setWeather(response.data)})
},
[city])
console.log(`The value of the weather var is ${JSON.stringify(weather)}`)
return (
<div>
<h1>Weather in {city}</h2>
<p>temperature: {weather.current.temp_c} Celsius</p>
<img src={weather.current.condition.icon} alt="weather forecast"/>
<p>wind speed: {weather.current.wind_mph} mph</p>
<p>wind dir.: {weather.current.wind_dir}</p>
</div>
)
}
【问题讨论】:
-
您可能会遇到错误,天气似乎是一个数组(基于其初始值)并且您正在将其作为对象访问
-
看看这个lifecycle diagram 并注意“返回/渲染”在“渲染”阶段被调用和处理,效果在“提交”阶段被调用,其中
componentDidMount和componentDidUpdate被调用。这就是 React 组件生命周期的运作方式。效果总是在组件渲染后调用。您的weather状态也被定义为一个数组,但您可以像访问返回的对象一样访问它。 -
@DrewReese 谢谢,总是在渲染之后出现的效果可以解释它。 (顺便说一句,
weather确实应该是一个对象,我只是将它初始化为一个数组作为一个错误。编辑了我的 OP,以便weather被初始化为一个空对象而不是空数组(我会把它留给其他人看看并从中学习,如果不是因为它分散了问题的真正核心,你也已经解决了)) -
“标准”方式是在组件挂载时进行“异步”调用以获取数据,无论是在基于类的组件中的
componentDidMount中,还是在useEffect的第一次触发中挂钩功能组件。您必须在尚未填充数据时处理条件渲染。 -
那将是一个正确的确认。
标签: reactjs asynchronous promise axios use-effect