简体   繁体   中英

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?

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. At first it only happened on Class Components but now will be default for functional components as well. It is by design when using useState or other Hooks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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