簡體   English   中英

使用useEffect時,react組件會渲染幾次

[英]The react component renders several times when using useEffect

我使用帶有鈎子的功能性React組件。

const [loaded, setLoaded] = React.useState(null);
const [title, setTitle] = React.useState(title);

React.useEffect(() => {
    //...
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => {
          setLoaded(true);
          setTitle(title);
      });
}, []);

在這種情況下,組件將渲染兩次。 一方面,這似乎是合乎邏輯的。

但是我在這個組件中也有一個復選框處理程序

const changeHandler = event => {
    //...
    setTotal(new_total);
    setError(false);
};

在這種情況下,盡管狀態也會更改2次,但不會進行兩次渲染。 我不明白為什么會這樣。

PS

解決這個問題沒有問題,我想知道為什么這就是事實

UPD

如果我設置為useEffect

setLoaded(true);
setTitle(title);
setTitle2(title);
setTitle3(title);

將重新渲染4次,如果我在changeHandler設置

setTotal(new_total);
setError(false);
setError2(false);
setError3(false);

將重新渲染1次

調用useState()掛鈎的setter方法的useState()是,這樣做會觸發組件重新呈現。

一種避免冗余重新渲染的解決方案是合並組件狀態,如下所示:

function functionalComponent() {

    /* Merge both values into common "state object */
    const [{ loaded, title }, setState] = React.useState({ 
        loaded : null, 
        title : "inital title" 
    });

    React.useEffect(() => {

        /* 
        Single call to setState triggers on re-render only. The
        value of "new title" for title could have been set in the
        inital state, however I set it here to show how combined
        state can be updated with a single call to setState()  
        */
        setState({ loaded : true, title : "new title" })

        /*
        setLoaded(true);
        setTitle(title);
        */
    }, []);

    /* Use loaded and title variables as needed during render */
    return <div>{ loaded } - { title }</div>
}

React將事件處理程序包裝在對unstable_batchedUpdates()的調用中,以便您的處理程序在回調中運行。 該回調內部觸發的任何狀態更新將被分批處理。 在該回調之外觸發的任何狀態更新都不會被批處理。 超時,承諾和異步函數最終將在該回調之外執行,因此將不進行批處理。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM