首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在多次调用的ReactJS内的函数

问在多次调用的ReactJS内的函数
EN

Stack Overflow用户
提问于 2020-10-19 13:10:17
回答 2查看 76关注 0票数 1

我使用Ionic React并使用插件加载本地数据。我只调用该函数一次,但它被调用了很多次

Main.jsx

代码语言:javascript
复制
import React ,{useState} from 'react';
import {
    IonApp, 
    IonHeader,
    IonTitle,
    IonToolbar,
    IonContent,
    IonInput,
    IonList,
    IonItem,
    IonLabel,
    IonButton
} from '@ionic/react';
import 'capacitor-secure-storage-plugin';
import { Plugins } from '@capacitor/core';
const { SecureStoragePlugin } = Plugins;


    const MainPage=  () => {
        const [username,setUsername]=useState("h");
        const [token,setToken]=useState("blah");
        const bogusFunctionForAsyncOperations = async () => 
        {   console.log("Hello world");
            let temp;
            let key='username';
            temp=await SecureStoragePlugin.get({ key })
              .then(value => {
                 console.log(value.value," Got username from storage  at MainPage");
                return value;
              })
              .catch(error => {
                console.log('Item with specified key does not exist.');
                return ( "Error at MainPage .The key is "+key);
              });
              setUsername(temp.value);
        }
        bogusFunctionForAsyncOperations();
        return (
            <>
                <p>Hello {username}! </p>
            </>
            );
        };
    export default MainPage;

日志

代码语言:javascript
复制
    main.jsx:23 Hello world
    main.jsx:28 testuser  Got username from storage  at MainPage
    main.jsx:23 Hello world
    main.jsx:28 testuser  Got username from storage  at MainPage
    main.jsx:23 Hello world
    main.jsx:28 testuser  Got username from storage  at MainPage

1.我如何解决这个问题?2.有没有更好的方法来做await,而不是把所有的await都放在一个“异步”中?谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-10-19 13:16:44

把这个放到你的React.useEffect里

代码语言:javascript
复制
React.useEffect(() => {
   bogusFunctionForAsyncOperations();
}, []);

问题是,因为你的函数在你的第一次渲染中运行,它再次更新状态,从而触发另一次重新渲染,并在那里开始无限循环。

票数 2
EN

Stack Overflow用户

发布于 2020-10-19 13:17:30

将函数调用bogusFunctionForAsyncOperations()放入useEffect()中

每次设置状态时,它都会被执行

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64421480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档