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

时间:2021-02-13 07:28:53

标签: reactjs axios react-hooks react-state

我有这个代码,在我完成 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;

<块引用>

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

1 个答案:

答案 0 :(得分:3)

你需要在 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 并将依赖项数组设为空,您可以实现这一点。

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