如何使用 MobX 重新渲染取消选择和选择的项目?

How to re-render only deselected and selected items with MobX?

我有 the following app 允许我点击列表中的待办事项并且一次只有一个待办事项 selected:

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>;
  }
}

当我 select 一个新的待办事项时,整个待办事项列表会重新呈现。有没有什么方法可以重新呈现 selected 和 deselected 待办事项,而不用额外的数据使状态混乱?

不是在每个 TodoView 依赖的 App 组件中有一个 selected observable,而是可以使用一个 observable map 并给每个 TodoView 一个自己的关键观察。将此 map 作为道具传递给 TodoView 并检查 map 是否将待办事项的 ID 作为键。 This way only the selected and deselected todos will be re-rendered:

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>;
  }
}