我多次输出相同组件的循环。
目标:当SomeComponent
组件的单个实例的内容更新时,我想避免重新呈现组件的整个循环。如果可能的话,我还想避免重新呈现Panel
围绕新更新的的高阶组件SomeComponent
。
问题:目前,当我这样做时,所有人Panel
和他们的孩子一起重新渲染SomeComponent
。
函数创建组件数组:
createPanels = () => {
const numberOfPanels = 4
const panelsArray = []
for (let index = 0; index < numberOfPanels; index++) {
panelsArray.push(
<Panel>
<SomeComponent theProp={willBeDynamic}/>
</Panel>
)
}
return panelsArray.map((panel) => panel)
}
渲染功能:
render(props) {
return (
<div>
<Wrapper>{this.createPanels()}</Wrapper>
</div>
)
}
是否有一个我尚未学习的功能可以使我仅重新渲染一个Panel
,SomeComponent
还是应该以另一种方式构造代码?(假设其中包含的逻辑SomeComponent
根据接收到的道具呈现不同的内容)。
注意:我使用数组的原因是在某些情况下该数组中项目的顺序需要颠倒。
谢谢
可以将React组件包装在React.memo中,以通过记忆结果来提高性能。它检查道具更改:
这只会重新渲染更新的项目:
const Panel = ({ children }) => {
console.log("panel");
return <div>{children}</div>;
};
const SomeComponent = ({ theProp }) => {
console.log(theProp);
return <div>Some Component Data {theProp}</div>;
};
const PanelComponent = React.memo(({ theProp }) => (
<Panel>
<SomeComponent theProp={theProp} />
</Panel>
));
export default function App() {
const [data, setData] = useState([
{ theProp: "theProp 1" },
{ theProp: "theProp 2" },
{ theProp: "theProp 3" }
]);
useEffect(() => {
setTimeout(() => {
setData(prev => {
prev[0].theProp = "theProp Updated";
return [...prev]; // force update item 0
});
}, 2000);
}, []);
return (
<div>
{data.map((item, index) => (
<PanelComponent theProp={item.theProp} key={`item_${index}`} />
))}
</div>
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句