在调用之前反应条件渲染

问题描述 投票:0回答:1

条件是在fetch之前调用,所以我无法在页面上渲染图像。

我需要根据API数据设置一个图标。

  1. 调用天气数据API,然后将其设置为

    weatherData
    状态

  2. 根据数据设置天气图标/图像

这里的图标/图像是外部的,所以我使用switch语句来定义图标

import rain from "../src/Images/rain.jpg";
import fog from "../src/Images/fog.jpg";
import snow from "../src/Images/snow.jpg";
import wind from "../src/Images/wind.jpg";
import cloudy from "../src/Images/cloudy.png";
import sn from "../src/Images/sn.jpg";

let newBG;


 useEffect(() => {
    fetchData             // <==fetching data 
  }, []);


  useEffect(() => {
    setbgTheme(newBg);    // <== setting Bg
  }, [newBG]);



switch (weatherData? weatherData.currentConditions.icon: "sn") {
      case "rain":
        newBg = rain;
        break;
      case "fog":
        newBg = fog;
        break;
      case "cloudy":
        newBg = cloudy;
        break;
      case "snow":
        newBg = snow;
        break;
      case "wind":
        newBg = wind;
        break;
      case "sn":
        newBg = sn;
        
    }

这里 switch 语句是在 fetch 之前调用的,所以我对 switch 语句使用了 setTimeout 函数。

仍然没有渲染。

reactjs fetch render
1个回答
0
投票

这应该位于具有 async-await 或 Promise 的单个函数内。我们来看一段代码:

import rain from "../src/Images/rain.jpg";
// ...
import sn from "../src/Images/sn.jpg";
let newBG;

useEffect(() => {
    // use async on the function where we are using the `await` keyword
  const handleFetchDataAndSetImage = async () => {
    // let's wait for the data from API using await
    const { data } = await axios.get("/your/api/endpoint"); // or you can use fetch instead of axios
    // now we have data
    setBgTheme(newBg); // or you can just use switch case directly with `setBgTheme` without using new variable `newBg` 
  };

  handleFetchDataAndSetImage();
}, []);


switch (weatherData ? weatherData.currentConditions.icon : "sn") {
  case "rain":
    // ...
    newBg = sn;
}
© www.soinside.com 2019 - 2024. All rights reserved.