小编典典

如何解决 useStae 无限渲染错误

javascript

我试图更改特定 url 中的文本值。所以我尝试使用 useState() 但我收到了这个错误。

react-dom.development.js:16317 Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

如何解决此问题并更改特定 URL 的值?我将在下面向您展示我的代码。

import React,{useState} from 'react';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';


function MK(){

    const url = window.location.href;
    const [name,setName] = useState();
    if(url.includes('point')){
        //I want to change value here but getting error
        setName('error point');
    }

    return(
        <Form>
            <Form.Group className="mb-3" controlId="formBasicEmail">
                <Form.Label style={{color : 'white'}} id="label1">{name} 이름</Form.Label>
                <Form.Control style={{width:'30%'}}/>
            </Form.Group>

            <Form.Group className="mb-3" controlId="formBasicPassword">
                <Form.Label style={{color : 'white'}}> 설명</Form.Label>
                <Form.Control style={{width : '30%'}} as="textarea" rows={3} />
            </Form.Group>

            <Form.Group controlId="formFile" className="mb-3">
                <Form.Label style={{color : 'white'}}> 사진</Form.Label>
                <Form.Control style={{width : '30%'}} type="file" />
            </Form.Group>

            <Button variant="primary" type="submit">
            Submit
            </Button>
      </Form>
    );
}
export default MK;

阅读 174

收藏
2022-07-25

共1个答案

小编典典

问题是如果setName()调用了。它触发页面的呈现并再次被调用setName()。这意味着钩子 useState() 在每次渲染时都会调用,因此它会再次重新渲染并且被无限期地调用。为避免这种情况,您可以使用另一个 react State hook useEffect()。当状态加载示例时仅触发一次:

useEffect(() => {
    if(url.includes('point')){
        setName('error point');
    }
  }, []);

[]意味着 useEfect() 方法中的定义将只运行一次。

有关无限重新渲染的更多信息,请参见此处链接

2022-07-25