我正在通过一个数组进行映射,该数组将为数组中的每个项目返回JSX组件。在运行时,我想传递值。如果它们与单个项目的值匹配,则会修改其单个组件。
我正在尝试找到一种无需重新渲染所有组件即可实现这一目标的方法,目前这是因为道具发生了变化
我曾尝试在类组件中使用 shouldComponentUpdate ,但是似乎这种方式只能将prevState和prevProps与相应的更改进行比较。我进一步考虑了Map函数中的 useMemo ,因为它嵌套在map函数中,所以没有用。
objects: MyObjectInterface[] = [
{
aProp: 'test'
}
]
父项:
const toParent=[1,2,4,5]
子组件:
function parent({ toParent }) {
const [myNumbers] = useState([1,2,3,4, ..., 1000]);
return (
<div>
{myNumbers.map((number, index) => (
<Child toChild = { toParent } number = { number }
index= { index } key = { number }/>
))}
</div>
)
}
答案 0 :(得分:1)
我的问题的解决方案是使用React.memo HOC并比较彼此的属性并将其导出为React.memo(Child, propsAreEqual)
。
这样,可以避免其他方法,例如findElementbyId(在任何情况下均不建议使用)和应该针对地图功能中特定项目的shouldComponentUpdate。 性能也相当不错。使用此方法可以将渲染时间从每250ms 40ms减少到大约2ms。
在子组件中:
function Child(){...}
function propsAreEqual(prev, next) {
//returning false will update component, note here that nextKey.number never changes.
//It is only constantly passed by props
return !next.toChild.includes(next.number)
}
export default React.memo(Child, propsAreEqual);
或者,如果还应检查其他语句:
function Child(){...}
function propsAreEqual(prev, next) {
if (next.toChild.includes(next.number)) { return false }
else if ( next.anotherProperty === next.someStaticProperty ) { return false }
else { return true }
}
export default React.memo(Key, propsAreEqual);