UseEffect函数更新状态变量

时间:2020-10-20 18:58:51

标签: reactjs react-hooks state use-effect

我是新来的反应者,每次渲染函数时,我都需要更新update状态变量。此变量用作组件的支持。

代码是

function Cal(props) {
     const [allEvents, setEvents] = useState({ events: [] });
     const [currentYear, setCurrentYear] =useState(moment().year().toString());
     useEffect(() => {
    getEvents();
 
  }, [currentYear]);
  async function getEvents() {
    const yearStart = `${currentYear}-01-01`;
    const yearEnd = `${currentYear}-12-31`;
    const data = await fetchEvents(yearStart, yearEnd, 'Discount', currentLang);
    console.log('data:', data);
    setEvents(data);
    console.log('allEvents:', allEvents);
  }
   return (
       <ChildComp
          eventData={allEvents}
        />
   );
}

更新: 每当当前年份的值更改时,我都需要调用getEvents函数。当我控制台记录数据值时,我会看到响应数据。但是当我控制台记录allEvents时,我总是看到一个空数组。我看不到数据更新的价值。 ? 任何帮助将不胜感激。

谢谢

3 个答案:

答案 0 :(得分:0)

在useEffect之外调用该函数。

function Cal(props) {
         const [allEvents, setEvents] = useState({ events: [] });

async function getEvents() {
      const yearStart = `${currentYear}-01-01`;
      const yearEnd = `${currentYear}-12-31`;
      const data = await fetchEvents(yearStart, yearEnd, 'Hard Discount', currentLang);
      console.log('data:', data);
      setEvents(data);
      console.log('allEvents:', allEvents);
    }


     useEffect(() => {
   
    getEvents();
  }, [allEvents]);
   return (
       <ChildComp
          eventData={allEvents}
        />
   );
}

例如;

useEffect(() => {
    getCountries();
  }, []);

  const getCountries = async () => {
    const response = await fetch("https://covid19.mathdro.id/api/countries");
    const data = await response.json();
    const arrayOfCountry = data.countries;

    setCountries(arrayOfCountry);
    setLoading(false);
  };

答案 1 :(得分:0)

如果我正确理解,则仅在首次呈现组件后才需要获取异步数据,因此将useEffect钩子更改为空数组,它将触发几乎等效的“ componentDidMount()”上的钩子< / p>

function Cal(props) {
     const [allEvents, setEvents] = useState({ events: [] });

     useEffect(() => {
    async function getEvents() {
      const yearStart = `${currentYear}-01-01`;
      const yearEnd = `${currentYear}-12-31`;
      const data = await fetchEvents(yearStart, yearEnd, 'Hard Discount', currentLang);
      console.log('data:', data);
      setEvents(data);
      console.log('allEvents:', allEvents);
    }
    getEvents();
  }, []);
   return (
       <ChildComp
          eventData={allEvents}
        />
   );
}

答案 2 :(得分:0)

根据您的代码,useEffect具有[allEvents]依赖项,这意味着每次allEvents更改getEvents()都会被调用,

我相信您只是在组件首次安装时需要它,因此只需删除依赖项

useEffect(() => {
   
    getEvents();
  }, [allEvents]);