Error: Too many re-renders. React limits the number of renders to prevent an infinite loop when using useState()

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop when using useState()

App.js:
import React, { useState } from "react";
import Login from "./Login";

function App() {

  const [id, setId] = useState();

  return (
    <>
      {id}
      <Login onSubmit={setId()}/>
    </>
  );
}

export default App;

Login.js:
import React, { useRef } from 'react'
import { Container, Form, Button } from "react-bootstrap";

export default function Login({ onIdSubmit }) {

    const idRef = useRef();

    function handleSubmit(e) {
        e.preventDefault()

        onIdSubmit(idRef.current.value)
    }

    return (
        <Container className="align-items-center d-flex" style={{height: "100vh"}}>
            <Form  className="w-100" onSubmit={handleSubmit}>
                <Form.Group>
                    <Form.Label>
                        Enter your Id
                    </Form.Label>
                    <Form.Control type="text" ref={idRef} required/>
                </Form.Group>
                <Button type="submit" style={{marginRight: "5px", marginTop: "5px"}}>Login</Button>
                <Button variant="secondary" style={{marginTop: "5px"}}>Create A New Id</Button>
            </Form>
        </Container>
    )
}

似乎错误在 onSubmit={setId()} 上的 App.js 中,因为当我注释掉它时它起作用了。

这里的想法是,当您单击“登录”按钮时,<Form.Control type="text" ref={idRef} required/> 中的值存储在 App.js 的 useState 中。我可以在没有获得 Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. 的情况下执行此操作吗?

只需使用不带括号的 setId ()。当您在函数旁边写上括号时,这意味着您实际上是在调用该函数,这会导致重新渲染。但在您的情况下,您只想将函数的引用传递给子组件。

<Login onIdSubmit={setId}/>

并将 onSubmit 重命名为 onIdSubmit 正如@Vaibhav 评论的那样。