【问题标题】:How can I solve useStae infinite rendering error如何解决 useStae 无限渲染错误
【发布时间】:2022-07-25 18:27:40
【问题描述】:

我试图更改特定 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;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您通过设置条件值来导致无限重新渲染。

    你需要为此使用 useEffect 钩子:

    React.useEffect(() => {
        if(url.includes('point')){
            //I want to change value here but getting error
            setName('error point');
        }},[url]) //If url changes, run useEffect
    
    

    每次状态变化和初始渲染都会运行使用效果,如果有变化,您可以在其中执行一些操作。在这种情况下,如果 url 发生变化,运行里面的代码

    【讨论】:

      猜你喜欢
      • 2022-12-31
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 2020-09-30
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      相关资源
      最近更新 更多