我有the following app,允许我点击列表中的待办事项,一次只选择一个待办事项:
class State {
@observable todos = [
{ id: '1', description: 'Do this' },
{ id: '2', description: 'Do that' },
{ id: '3', description: 'Do this third thing' }
]
}
const state = new State();
const TodoView = observer(({ todo, isSelected, onClick }) => (
<div onClick={onClick}>
{ todo.description } { isSelected && ' (selected)' }
</div>
));
@observer
class App extends Component {
@observable selected = null;
render () {
return <div>
{ state.todos.map((todo) =>
<TodoView
key={todo.id}
todo={todo}
isSelected={this.selected === todo}
onClick={() => this.selected = todo} />
)}
</div>;
}
}
当我选择新的待办事项时,会重新呈现完整的待办事项列表。有没有办法只重新渲染选定和取消选择的待办事项,而不会使其他数据混乱?
答案 0 :(得分:1)
您可以使用可观察的selected
并为每个App
分配一个TodoView
组件而不是每个map
所依赖的TodoView
组件中的map
可观察对象自己观察的关键。将此TodoView
作为道具传递给map
并检查class State {
@observable todos = [
{ id: '1', description: 'Do this' },
{ id: '2', description: 'Do that' },
{ id: '3', description: 'Do this third thing' }
]
}
const state = new State();
const TodoView = observer(({ todo, selectedMap, onClick }) => (
<div onClick={onClick}>
{ todo.description } { selectedMap.has(todo.id) && ' (selected)' }
</div>
));
@observer
class App extends Component {
selectedMap = observable.map({});
onClick = (todo) => {
this.selectedMap.clear();
this.selectedMap.set(todo.id, todo);
};
render () {
return <div>
{ state.todos.map((todo, idx) =>
<TodoView
key={todo.id}
todo={todo}
selectedMap={this.selectedMap}
onClick={() => this.onClick(todo)} />
)}
</div>;
}
}
是否将待办事项的ID作为关键字。 This way only the selected and deselected todos will be re-rendered:
QSerialPort