简体   繁体   English

反应:内容加载两次

[英]React: content loading twice

I created a button that change the state of a variable on click, the problem is: when i click on it, the console.log prints the variable twice , how do i avoid this problem?我创建了一个按钮,在单击时更改变量的 state,问题是:当我单击它时,console.log 会打印两次变量,我该如何避免这个问题?

My code:我的代码:

    function List(){
        const [documents, setDocuments] = useState([])
        var [isToggled, setIsToggled] = useState(true)

        return (
            <div className={ isToggled ? "d-flex" : "d-flex toggled"} id="wrapper">
                { console.log(isToggled)}

                <div className="bg-light border-right" id="sidebar-wrapper">
                    <div className="sidebar-heading"> Rascunhos </div>
                    <div className="list-group list-group-flush">
                        <tr className="d-flex conteudo">
                            <td className="list-group-item descricao">Dashboard</td>
                            <td className="list-group-item qnt">1997</td>
                        </tr>
                    </div>
                <div className="btn-group">
                    <button className="btn btn-primary btnCarregar">Carregar</button>
                </div>
                </div>  
                <button className="btn btn-primary btnToggle ml-2 mt-2" onClick={ () => setIsToggled(!isToggled) } id="menu-toggle">></button>
            </div>
        )     
    }

I had this issue as well and it had to do with StrictMode being enabled which gets added by default when you create a new React app.我也遇到了这个问题,它与启用的 StrictMode 有关,当您创建新的 React 应用程序时默认添加它。 At first it only happened on Class Components but now will be default for functional components as well.起初它只发生在 Class 组件上,但现在也将是功能组件的默认设置。 It is by design when using useState or other Hooks.这是使用 useState 或其他 Hooks 时的设计。

https://github.com/facebook/react/issues/15074 https://github.com/facebook/react/issues/15074

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM