对REACT中的变量范围感到困惑?

时间:2020-07-06 04:10:29

标签: reactjs state

我在return之前定义了一个const(但是当我尝试渲染它时,得到未定义的错误。

我正在努力应对REACT的概念。在RETURN之前定义的任何常量或变量都无法在??

中进行渲染

是否只有setState变量可用于渲染?

这里是代码。.我从API数据中保存了var countryname,但是当我尝试呈现它时,UNDEFINED说

./ src / components / CountryPanel.jsx 行83:49:未定义“国家/地区名称” no-undef

export default function CountryPanel(props) {
  const classes = useStyles();
  
  let countryCode = props.countryCode

  let url =
      "https://api.thevirustracker.com/free-api?countryTotal=" + countryCode;
  const [globalData, setGlobalData] = useState({});
  const [countryName, setCountryName] = useState("");
    
  useEffect(() => {
   
    getData(url);

    async function getData(url) {
      const response = await fetch(url);
      let data = await response.json(); // convert to json
      const countryname = data.countrydata[0].info.title;
      delete data.countrydata[0].info;
      setCountryName(countryname);
      setGlobalData(data.countrydata[0]);
    }
  }, []);

  return (
    <div className={classes.root}>
      <h3>
        Stats for: {countryCode} {countryName} {countryname}
      </h3>

尽管我从API数据中保存了它,但最后三个是未定义的 const countryname = data.countrydata [0] .info.title; (..name-n小写)

2 个答案:

答案 0 :(得分:1)

问题在于countryname(与countryName分开)仅作用于函数getData。 JavaScript中的变量的作用域取决于它们在其中定义的功能/块,具体取决于您声明变量的方式(var vs let / const)。在这种情况下,countryName在组件中的任何位置都可用,而countryname仅在getData中可用。这是一种JavaScript主义,与使用React无关。

答案 1 :(得分:0)

首先,setState不是变量,但是我们需要const来定义state

例如:const [isLoading, setIsLoading] = useState(true);

isLoading默认为true,并且可以通过setIsLoading进行修改。


另一个例子是const foo = 'bar';

在这种情况下,foo无法更改为其他值。


希望您能理解