javascript - 如何有条件地更新 react 列表组件

标签 javascript reactjs react-hooks

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

相关文章:

node.js - 如何修复 "Response to preflight request doesn' t 通过访问控制检查 : It does not have HTTP ok status"error in react app with nodejs api

javascript - 如何为 React 生产重定向端口

javascript - 当窗口宽度小于 600px 时,如何禁用 MUI 网格元素堆叠

javascript - 更简单的方法来编写一系列图像 javascript

javascript - 使用 jQuery 和 AJAX 调用 PHP 类方法并获取返回值

javascript - 使用 gulp 4 .series 时,函数调用中的参数有何意义?

javascript - 如何根据按下的按钮填充输入文本字段数据

reactjs - 如何使用 React Hooks 将焦点集中在下一个渲染上

javascript - useMemo 与 useEffect + useState

reactjs - React Hooks Form Reset 不要将 Select 设置为初始值