简体   繁体   English

如何在 react.js 的回调中调用 UseState 钩子的 state 更新程序 function

[英]how to call UseState hook's state updater function inside a callback in react.js

I'm having this code where after I get the http request fulfilled, I'm calling the state updater function ie, setUserName with the response I get from the async function. I'm having this code where after I get the http request fulfilled, I'm calling the state updater function ie, setUserName with the response I get from the async function. But I see that UsernameGenerator() just gets called repeatedly like in an infinite loop.但是我看到UsernameGenerator()就像在无限循环中一样被重复调用。 I think somehow repeated rendering is taking place here because I have used the UserName as a value for an input in my code.我认为这里发生了某种重复渲染,因为我在代码中使用了 UserName 作为输入的值。

The thing I want is to set the res as the initial value for the state variable and after setting the value once UsernameGenerator() should never be called again.我想要的是将 res 设置为 state 变量的initial value ,并且在设置了一次UsernameGenerator()后,永远不应再次调用该值。

Here is the snippet of my code这是我的代码片段

 import { useState } from "react"; import axios from "axios"; const SignUp = () => { const [UserName, setUserName] = useState(""); const usernameGenerator = async () => { let username = await axios.get("https://localhost:5000/GenerateUserName"); return username.data.username; }; usernameGenerator().then((res) => { setUserName(res); return res; }).catch ((err)=>{ if(err) throw err; }); return ( <Input color="secondary" id="UserName" type="text" aria-describedby="User-Name" value={UserName} onChange={(e) => setUserName(e.target.value)} className={classes.input} /> ); } export default SignUp;

How do I avoid this infinite loop like condition and have the res as my initial value of the state variable.如何避免这种类似无限循环的情况,并将res作为 state 变量的初始值。

You need to put a call in useEffect hooks, like -您需要在 useEffect 挂钩中进行调用,例如-

import { useEffect } from "react";


useEffect(() => {
    usernameGenerator().then((res) => {
       setUserName(res);

    }).catch ((err)=>{
        // handle error here, instead of throwing
    });
}, []); // here you need to pass empty array as second parameter of useEffect to call it once

Explanation: What you want is to call API on the component mount so by using useEffect with dependency array as empty you can achieve this.说明:您想要的是在组件挂载上调用 API ,因此通过使用 useEffect 和依赖数组为空,您可以实现此目的。

Currently, you're calling it on every render and in the then callback you're updating state which is causing an infinite loop目前,您在每次渲染时调用它,然后在回调中更新 state 导致无限循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM