我使用Ionic React并使用插件加载本地数据。我只调用该函数一次,但它被调用了很多次
Main.jsx
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;日志
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 MainPage1.我如何解决这个问题?2.有没有更好的方法来做await,而不是把所有的await都放在一个“异步”中?谢谢!
发布于 2020-10-19 13:16:44
把这个放到你的React.useEffect里
React.useEffect(() => {
bogusFunctionForAsyncOperations();
}, []);问题是,因为你的函数在你的第一次渲染中运行,它再次更新状态,从而触发另一次重新渲染,并在那里开始无限循环。
发布于 2020-10-19 13:17:30
将函数调用bogusFunctionForAsyncOperations()放入useEffect()中
每次设置状态时,它都会被执行
https://stackoverflow.com/questions/64421480
复制相似问题