9

在一个列表中,当 selected item change 了,如何合适的捕捉到这个改变?

 3 years ago
source link: https://www.v2ex.com/t/786877
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  React

在一个列表中,当 selected item change 了,如何合适的捕捉到这个改变?

  yazoox · 1 天前 · 379 次点击

如图,比如,当前选中的是 "Category3 -> Layout1",因为选中了,所以有高亮背景显示,等等。

如果此时,我选择了另外一个 Item, 比如“Category2 -> Layout2”,则,如何通知 Category3 -> Layout1 取消“选中”状态,然后 Category2 -> Layout2 则变为选中状态?

本来我的想法是,在这个组件 /app 的全局,添加一个 selectedItem 和一个 previousSelectedItem 变量,专门用于维护”选中“状态,每次 有鼠标点击一个 Item 的时候,发送消息,改变 selected & previous selected item,再进行渲染。

这样的话,我可能需要有一个 map, key 是 item's id, value 就是这个 item 对象。当 selected 对象改变时,通过这个 map,和 key 找到对应的 item,然后 改变它的 state,这样,react 就会只 re-render 这两个对象了,而不是 render 所有的 items.

但感觉不是很”优雅“,所以,来请教一下大家。有没有更好的方法。

TreeView.png

p.s.
框架使用的是 react, redux or useReducer.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK