react.js 如何在回调中调用 UseState 钩子的状态更新函数

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

我有这段代码,在完成 http 请求后,我正在调用状态更新程序函数,即 setUserName 以及我从异步函数获得的响应。但是我看到 UsernameGenerator() 就像在无限循环中一样被重复调用。我认为这里会以某种方式重复渲染,因为我在代码中使用了 UserName 作为输入值。

我想要的是将 res 设置为状态变量的 initial value 并且在设置值一次后 UsernameGenerator() 永远不会再被调用。

这是我的代码片段

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.

您需要在 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

说明: 您想要的是在组件安装上调用 API,因此通过将 useEffect 与依赖项数组一起使用为空,您可以实现此目的。

目前,您在每次渲染时都调用它,而在 then 回调中您正在更新导致无限循环的状态