繁体   English   中英

如何有条件地更新反应列表组件

[英]How to conditionally update react list components

我有下面的 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 。

这是您的 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仅在道具更改时呈现。

请参阅更新的 JsFiddle并检查 console.log() s。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM