【问题标题】:i'm getting isssue while calling API in Useeffect in reactJs我在 reactJs 的 Useeffect 中调用 API 时遇到问题
【发布时间】:2021-07-22 14:07:58
【问题描述】:

我在 useeffect 中调用了两个方法,但是当 api1 被调用时,它会被执行直到 await axios.put 然后 api2 被调用没有得到 api1 的响应。在得到 api2 的响应后,它会转到 api1 响应并得到 undefined

的响应
useEffect(() => {       
          api1();
       api2();
    }, [])

const api1 = async () => {
        try {
            var requestModel = JSON.stringify({ UserId: userid, MenuName: menuname });
            var requestBody = security.encrypt(requestModel);
            axios.myHashData = security.computedHmac256(requestBody);
            var config = { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }
            await axios.put(axios.controllername + 'methodname', requestBody, config, { withCredentials: true })
                .then(response => {
                    if (response.status === 200) {
                        //setapidata(response.data);
                    }
                });
        } catch (error) {
            console.error(error.message)
        }
    }
 const api2= async () => {
        try {
            var requestModel = JSON.stringify({ UserID: userid });
            var requestBody = security.encrypt(requestModel);
            axios.myHashData = security.computedHmac256(requestBody);
            var config = { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }
            await axios.post(axios.controllername + 'methodname', requestBody, config, { withCredentials: true })
                .then(response => {
                    if (response.status === 200) {
                        setapidata(response.data);
                        GetApis();
                    }
                });
        } catch (error) {
            console.error(error.message)
        }
    }

【问题讨论】:

  • 不太清楚您的 API 函数从哪里调用,或者它们试图使用什么响应。此外,如果api2 应该在api1 之后使用来自api1 的数据调用,为什么不在api1 中调用呢?

标签: node.js reactjs axios frontend


【解决方案1】:

如果您想在调用api2 之前等待api1 执行,您需要更改useEffect 的代码,如下所示

useEffect(async() => {
  await api1();
  await api2();
}, [])

useEffect(() => {
  api1().then(() => api2());
}, [])

若要正确处理错误,请在使用 await 时使用 useEffect 内的 try-catch 块,如果使用 .then,则使用 catch

另外,另一个建议是,如果您在 useEffect 中使用函数,请确保该函数在同一个 useEffect 块内定义,或者通过 useCallbackuseMemo 进行记忆

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2020-11-03
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    相关资源
    最近更新 更多