【问题标题】:Call function in useEffect only after previous are finished仅在前一个完成后调用 useEffect 中的函数
【发布时间】:2020-10-23 00:45:37
【问题描述】:

我的文件中有这种格式的 useEffect

    useEffect(() => {
     async function func1(){
                    //fetching data from database storing it in variable
        const options = {
                  headers: {
                    Accept: "application/json",
                    "Content-type": "application/json",
                  },
                };
        
                fetch(process.env.REACT_APP_DB_URI + "/icty/" + setzip, options)
                  .then((res) => res.json())
                  .then(
                    (result) => {
        ..... setAddressCurrent(result)
        
                }
              
                async function func2 (){
                     if (user.address) {
                  const data = user.address;
                  let zip;
                  var bar = new Promise((resolve, reject) => {
                    Object.keys(data).forEach(function (key, index, array) {
                      if (data[key].types) {
                        data[key].types.forEach((x) => {
                          if (x === "route") {
                            Cookies.set("street", data[key]["long_name"]);              
                          }
                          if (x === "street_number") {
                            Cookies.set("street_number", data[key]["long_name"]);
                          }
                          
                        });
                      }
                    });
                  }); 
               if(addressCurrent === user.address) return 1;
                  return bar.then(() => {
                    return zip;
                  });
                }
                }
        
               
                func1()
                func2() //------> how to call this one after func1 is finished doing all job
            }, []);

由于问题 func2 在 func1 完成之前被调用,我有未定义的变量。 有人知道如何在 React Hooks 中轻松解决这个问题吗? 修改后的代码

【问题讨论】:

  • 由于这些返回承诺,您需要使用func1().then(() => func2())

标签: reactjs react-hooks use-effect


【解决方案1】:

我认为问题在于您期望 func2 在同一个钩子执行中与组件状态一起执行,并且您无法确定在调用 func2 之前状态是否已更新。

你的逻辑如下:

func1() ==> sets state
<you expect the state to be updated for func2>
func2() ==> uses state

相反,您应该如下呈现您的逻辑。

useEffect(() => {
 async function func1() { /* function body that changes stateUpdatedByFunc1 */ }

 func1()
}, []) // only executes on component mounting phase

useEffect(() => { 
 async function func2()  { /* function body that depends on stateUpdatedByFunc1 */ }

 if (stateUpdatedByFunc1) {
  func2() // only call func2 if the state is not undefined or null
 }
},[stateUpdatedByFunc1]) // this gets executed after updating the state

另外,请记住将await 放在您希望花费时间的任何地方。例如,您没有使用await fetch(...),这肯定会使func1 在您预期之前返回。

【讨论】:

  • 对了,应该在哪里调用func1()自动启动呢?
  • 在另一个钩子里面,例如useEffect(() => { /* 调用func1 }, []),它只在组件挂载时执行。
  • 能否将其添加到答案中,以便我接受
  • 已添加!我还完成了更多关于定义等的内容
【解决方案2】:

你不能在 react 钩子中运行异步代码,你需要将函数外包到效果之外并在那里使用异步

async function runFunction() {
    function func1 (){
        //do something here
    }

    function func2(){
        //do some stuff here
    }

    await func1()
    await func2() //------> how to call this one after func1 is finished doing all job
}
 

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

【讨论】:

  • 不幸的是,在 func1 中的 func1 之前仍然调用 func2 有很多获取数据并设置它,在我设置它之后,我调用 func2 并且有错误变量未定义
  • @HardRock func2 中未定义什么变量?
  • 亲爱的@Shmili Breuer 我修改了一点代码,问题是当我设置变量并且在function2中设置了一个调用时,它没有定义
猜你喜欢
  • 2011-06-27
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 2019-03-22
相关资源
最近更新 更多