我有下面的 React 应用程序 ( jsfiddle ):
const ListItem = (props) => {
return (
<div className={props.active ? "active" : ""}>Item {props.index}</div>
)
}
const initialItems = ["item1", "item2", "item3", "item4", "item5"]
const App = (props) => {
const [activeIndex, setActiveIndex] = React.useState(0);
const goUp = () => {
if(activeIndex <= 0) return;
setActiveIndex(activeIndex - 1);
}
const goDown = () => {
if(activeIndex >= initialItems.length - 1) return;
setActiveIndex(activeIndex + 1);
}
return (
<div>
<p>
<button onClick={goUp}>Up</button>
<button onClick={goDown}>Down</button>
</p>
<div>
{initialItems.map((item, index) => (
<ListItem active={index === activeIndex} index={index} key={index} />
))}
</div>
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('container')
);
使用按钮可以突出显示当前列表元素。当前方法的问题在于,在每次事件索引更改时,它都会重新呈现完整列表。在我的例子中,列表可能非常大(数百项)且布局更复杂,这会带来性能问题。
如何修改此代码以使其仅更新特定的列表项组件而不触发所有其他组件的重新呈现?我正在寻找没有第三方库且没有直接 DOM 操作的解决方案。
最佳答案
您可以使用 React.memo() 将 ListItem 包装为 here .
这是您的 ListItem 组件,
const ListItem = (props) => {
return (
<div className={props.active ? "active" : ""}>Item {props.index}</div>
)
};
通过使用 React.Memo(),
const ListItem = React.memo((props) => {
return (
<div className={props.active ? "active" : ""}>Item {props.index}</div>
)
});
在这种情况下,ListItem
仅在 props 更改时呈现。
参见 updated JsFiddle并使用 console.log() 进行检查。
关于javascript - 如何有条件地更新 react 列表组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59304713/