【问题标题】:Cannot assign fetched data to useState on React [duplicate]无法将获取的数据分配给 React 上的 useState [重复]
【发布时间】:2021-12-31 09:33:35
【问题描述】:

所以我遇到了这个问题。我正在使用 axios 获取数据并希望将其分配给 useState。但是,包括 useEffect 中的 async 函数在内的所有方法都没有这样做。所以第一个 console.log(res.data) 很好地显示了所有信息。但是,第二个 console.log(weather) 显示一个空数组。有什么建议吗?

const App = () => {
  const [weather, setWeather] = useState([]);
  const [loading, setLoading] = useState(true);


  // Side effects
  useEffect(() => {
    axios
      .get("https://weather-app-tst.herokuapp.com/api/weather")
      .then((res) => {
        setLoading(false);
        console.log(res.data);
        
        setWeather(res.data);
        console.log(weather);
      })
      .catch((error) => console.log(error))
}, []);

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    weatherconsole.log 发生时尚未更新。 weather 应该在组件重新渲染后显示新值

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 1970-01-01
      • 2020-08-06
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2016-02-07
      相关资源
      最近更新 更多