1

I just started learning MobX today and I want to listen for all array changes (insertion, deletion, etc) using MobX. An example would illustrate this better:

const TodoList = ({todos}) => (
    <ul>
        {todos.map(todo => <li key={todo.id}>
            <TodoContainer todo={todo}/>
        </li>)}
    </ul>
);

module.exports = @observer class TodoListContainer extends React.Component {
    static contextTypes = {
        todoStore: React.PropTypes.instanceOf(TodoStore),
    };

    render() {
        let todos = this.context.todoStore.getTodos();

        return <TodoList todos={todos}/>;
    }
}

If I add or remove an item from todos, the list isn't updated. In order to make it update, I need to wrap observer around TodoList. The @observer on TodoListContainer doesn't do anything because I'm not accessing any observed properties. However, just for learning purposes, I want to use observer only on containers. I want to make the container rerender every time todos changes.

One way to do this is to do anything in TodoListContainer that iterates through all of todos. For example, in TodoListContainer.render, I can add for (let todo of todos) {} or todos.forEach(_ => _). Is there a better way to do it? For example, in Ember Data, you can do todos.[] to represent listening to all changes in todos.

4

1 回答 1

1

容器组件并不确切知道TodoList正在访问什么数据。在您的示例中,它循环遍历数组并访问id每个 todo 对象的属性。MobX 很擅长跟踪变化。因此,例如,如果您更改了第三个待办事项的 id: ,即使没有从数组中添加或删除任何项目todoStore.getTodos()[2].id = 3;,MobX 也会重新渲染。TodoList

一般来说,我建议添加@observer到所有组件并让 MobX 负责跟踪/重新渲染。

于 2016-11-07T06:44:01.563 回答