You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native如何避免非必要组件重渲染,让固定map内容仅渲染一次?

解决方案

导致map部分重复渲染的原因是:父组件状态ValueState更新时,会触发整个组件树的重新渲染,没有做缓存的静态元素也会跟着重新执行渲染逻辑。你可以通过以下两种方法实现map部分仅初始化渲染1次:

方法1:用useMemo缓存静态渲染结果

直接在当前组件内把map渲染的内容用useMemo包裹,依赖项设为空数组,仅在组件首次渲染时计算一次:

import { useState, useMemo } from 'react';

// 组件内部逻辑
const [ValueState, SetValueState] = useState(5); 

// 缓存静态列表,依赖为空仅初始化计算一次
const staticList = useMemo(() => {
  return [...Array(3)].map((index, el) => {
    return (<View key={index}><Text>Hello there</Text></View>)
  })
}, [])

return <View>
 <Text>{ValueState}</Text>
 <View>
  {staticList}
 </View>
</View>

注意:别忘了给map遍历的元素加唯一key属性,这是React列表渲染的强制要求。

方法2:提取静态部分为独立组件,用React.memo包裹

把不需要跟着状态更新的静态列表部分抽成单独组件,用React.memo做浅比较缓存,因为这个组件没有传入任何可变props,所以永远不会触发重渲染:

import { useState, memo } from 'react';

// 抽离的静态组件,memo包裹后props不变就不会重渲染
const StaticList = memo(() => {
  return [...Array(3)].map((index, el) => {
    return (<View key={index}><Text>Hello there</Text></View>)
  })
})

// 父组件内直接引用即可
const Parent = () => {
  const [ValueState, SetValueState] = useState(5); 
  return <View>
   <Text>{ValueState}</Text>
   <View>
    <StaticList />
   </View>
  </View>
}

内容的提问来源于stack exchange,提问作者user15573857

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:24:03