如何使用MobX仅重新呈现取消选择和选定的项目?

时间:2017-09-19 19:19:20

标签: javascript ecmascript-6 mobx mobx-react

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

当我选择新的待办事项时,会重新呈现完整的待办事项列表。有没有办法只重新渲染选定和取消选择的待办事项,而不会使其他数据混乱?

1 个答案:

答案 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