reactjs 在React中“state”赋值之前引用变量

jhiyze9q  于 2022-11-22  发布在  React
关注(0)|答案(1)|浏览(159)

我有一个react组件,它的开头是这样的:

function DetailedView({ country }) {
      useEffect(() => {
        axios
          .get(
            `https://api.openweathermap.org/data/2.5/weather?q=${country.capital[0]}&appid=${process.env.REACT_APP_WEATHER_API_KEY}`
          )
          .then((response) => setWeather(response.data));
      }, [country]);
    
      const [weather, setWeather] = useState({});

如您所见,有一个名为weather的州,我需要基于country属性进行查询,以接收首都城市,然后基于useEffect挂钩内的城市设置weather
在我的代码后面,我最终引用了weather变量。然而,最初它是未定义的,所以如果我试图在它上面使用点操作符从对象中检索属性,我会得到一个错误。为了解决这个问题,我最终不得不在从对象中访问属性之前检查对象是否为空:

{Object.keys(weather).length !== 0 ? (
    <>
      <p>Temperature: {weather.main.temp - 273}</p>
      <img
        src={`http://openweathermap.org/img/wn/${weather.weather[0].icon}@2x.png`}
        alt="icon"
      ></img>
      <p>Wind Speed: {weather.wind.speed} m/s</p>
    </>
  ) : (
    ""
  )}

这种方法是可行的,但似乎我在React中做了一些不符合习惯的事情。
谢谢你!

46scxncf

46scxncf1#

你的方法是正确的。我经常看到这样的代码。
您可能希望返回null而不是空字符串:

...
) : 
  null
}

有些人喜欢使用较短的语句进行条件渲染:

{(Object.keys(weather).length !== 0) && (
    <>
      <p>Temperature: {weather.main.temp - 273}</p>
      <img
        src={`http://openweathermap.org/img/wn/${weather.weather[0].icon}@2x.png`}
        alt="icon"
      ></img>
      <p>Wind Speed: {weather.wind.speed} m/s</p>
    </>)
}

相关问题