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

时间:2019-12-12 12:34:50

标签: javascript reactjs react-hooks

我下面有{jsfiddle)这个React应用:

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操作的解决方案。

1 个答案:

答案 0 :(得分:1)

您可以将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仅在更改道具时渲染。

查看updated JsFiddle并使用console.log()检查。