【问题标题】:Why is React's useEffect hook not called here before the function returns?为什么在函数返回之前这里没有调用 React 的 useEffect 钩子?
【发布时间】: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


【解决方案1】:

这是因为对 api 的调用是异步的,这意味着代码将在后台进行获取的同时继续执行,当返回响应时,它将在效果的 .then() 部分回调。

一种常见的做法是在加载数据时显示占位符:

const CityWeather = ({ city }) => {
  const [weather, setWeather] = useState(null);

  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>
      {!weather ? (
        <h3>Loading the weather!</h3>
      ) : (
        <>
          <h2>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>
  );
};

(另外,我注意到您将 weather 默认为数组 ([]),这可能会导致其他问题)

【讨论】:

  • 谢谢,这解决了我的问题。只是为了检查我的理解,事情总是按以下顺序发生吗? (1) 页面呈现并显示占位符。 (2)useEffect从API获取数据并调用setWeather。 (3) 由于weather因setWeather而改变,页面重新渲染,从而显示天气详情
  • 是的,这取决于 api 响应 weather 所需的时间。 1. 第一次渲染 - 没有weather,派发获取天气的 api 请求 2. 等待响应 3. 收到响应,状态更新,weather 在第二次渲染时显示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2020-03-30
  • 1970-01-01
相关资源
最近更新 更多