【问题标题】:how to call UseState hook's state updater function inside a callback in react.js如何在 react.js 的回调中调用 UseState 钩子的状态更新器函数
【发布时间】:2025-12-21 03:00:11
【问题描述】:

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

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

这是我的代码的 sn-p

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;

如何避免这种类似条件的无限循环并将​​res 设置为 我的状态变量的初始值。

【问题讨论】:

    标签: reactjs axios react-hooks react-state


    【解决方案1】:

    你需要在 useEffect hooks 中调用,比如 -

    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 和依赖数组为空你可以实现这一点。

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

    【讨论】:

      最近更新 更多