我试图避免重新渲染不必要的组件
例如:
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 次?
最佳答案
这取决于你不想重新渲染的函数取决于什么。在这种情况下,您的数组和映射函数不直接依赖于 ValueState
。
实现 1 次重新渲染的一种方法是使用 React.memo
仅渲染一次 map 功能的示例
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 呈现
一次。现在尝试通过按按状态更新
来更改ValueState
。 ArrayMapSection 不会重新渲染,因为 React.memo 仅在 props 更改时重新渲染
关于javascript - 如何避免在 React Native 中重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69546946/