我試圖避免重新渲染不必要的組件
例如:
const[ValueState,SetValueState]=useState(5); //hook
<View>
<Text>{ValueState}</Text>
<View>
{
[...Array(3)].map((index,el)=>{
return (<View><Text>Hello there</Text></View>)
})
}
</View>
</View>
每次我更改ValueState整個 map() 段的值時都會重新渲染
,我該如何避免這種情況并使 map() 段僅渲染 1 次?
uj5u.com熱心網友回復:
這取決于您不想重新渲染的功能取決于什么。在這種情況下,您的陣列和映射函式不直接依賴于ValueState.
實作 1 次重新渲染的一種方法是使用 React.memo
僅渲染地圖功能一次的示例
import React, { useState } from "react";
import { View, Text, TouchableOpacity } from "react-native";
const ArrayMapSection = React.memo(()=> {
console.log("ArrayMapSection rendered")
return [...Array(3)].map((index,el)=>{
return (<View><Text>Hello there</Text></View>)
});
})
const App = () => {
const [ValueState,SetValueState]=useState(5); //hook
return(
<View>
<Text>{ValueState}</Text>
<TouchableOpacity onPress={()=>SetValueState(Math.random())}>Press to state update</TouchableOpacity>
<View>
<ArrayMapSection />
</View>
</View>
)
};
export default App;
如果你運行這個程式,你ArrayMapSection rendered只會在控制臺中看到一次。現在嘗試ValueState通過按來更改Press to state update。ArrayMapSection 不會重新渲染,因為 React.memo 只會在 props 更改時重新渲染
更多資訊:https : //reactjs.org/docs/react-api.html#reactmemo
uj5u.com熱心網友回復:
創建一個自定義 react 組件,將陣列作為 prop 并將其映射到其他組件。
這樣,只有在陣列 prop 更改時才會重新渲染組件。
代碼示例:
const[ValueState,SetValueState]=useState(5);
<View>
<Text>{ValueState}</Text>
<CustomList array={[1,2,3]} />
</View>
export const CustomList = (array) => {
return (
<>
{
array.map((index,el)=>{
return (<View><Text>Hello there</Text></View>)
})
}
<\>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/310814.html
標籤:javascript 反应原生
