[英]Calling setState without triggering re-render
我將 UI state 存儲在 React 組件的state
中,比如this.state.receivedElements
是一個數組。 每當將元素推送到receivedElements
時,我都希望重新呈現。 我的問題是,當數組變空時,我可以不觸發渲染嗎?
或者一般來說,我可以只調用setState()
一次而不重新渲染,而在所有其他時間都重新渲染嗎? (有什么選擇,解決方法嗎?)
我已經閱讀了這個線程: https://github.com/facebook/react/issues/8598但沒有找到任何東西。
我想重新呈現每當一個元素被推向
receivedElements
。
請注意,如果您使用以下方法, 將不會得到重新渲染:
this.state.receivedElements.push(newElement); // WRONG
這違反了您不得直接修改狀態的限制。 您需要:
this.setState(function(state) {
return {receivedElements: state.receivedElements.concat([newElement])};
});
(它必須是回調版本,因為它依賴於當前狀態來設置新狀態。)
我的問題是,當數組為空時,是否可以不觸發渲染?
是的-在這種情況下不調用setState
。
聽起來好像receivedElements
不應成為您狀態的一部分,而是您可以單獨管理信息並在state
適當反映 。 例如,您可能已經在組件本身上receivedElements
了Element,在state
displayedElements
了state
。 然后:
this.receivedElements.push(newElement);
this.setState({displayedElements: this.receivedElements.slice()});
...和
// (...some operation that removes from `receivedElements`...), then:
if (this.receivedElements.length) {
this.setState({displayedElements: this.receivedElements.slice()});
}
請注意,如果this.receivedElements
為空,我們如何不調用setState
。
useRef
呢?
文檔說: useRef返回一個可變的 ref 對象,其 .current 屬性被初始化為傳遞的參數 (initialValue)。 返回的對象將在組件的整個生命周期內持續存在。
因此,如果您更改 useEffect 中的 ref 值,它將不會重新渲染組件。
const someValue = useRef(0)
useEffect(() => {
someValue.current++
},[])
useState 返回一個pair - 一個包含兩個元素的數組。 第一個元素是當前值,第二個元素是允許我們更新它的函數。 如果我們更新當前值,則不會調用渲染。 如果我們使用函數,則調用渲染。
const stateVariable = React.useState("value");
stateVariable[0]="newValue"; //update without rendering
stateVariable[1]("newValue");//update with rendering
目的
如果一個狀態變量被聲明為一個對象,那么我們可以改變它的第一個元素。 在這種情況下,不會調用渲染。
const [myVariable, setMyVariable] = React.useState({ key1: "value" });
myVariable.key1 = "newValue"; //update without rendering
setMyVariable({ key1:"newValue"}); //update with rendering
大批
如果一個狀態變量被聲明為一個數組,那么我們可以改變它的第一個元素。 在這種情況下,不會調用渲染。
const [myVariable, setMyVariable] = React.useState(["value"]);
myVariable[0] = "newValue"; //update without rendering
setMyVariable(["newValue"]); //update with rendering
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.