In the following sample code, unfinishedTodoCount
(under LoadContent
component) is not updated when todo items checked.
I dereference unfinishedTodoCount
in the render method of TodoListView so i think it must be tracked by mobx.
(I use "trigger rendering" button to force render() to update unfinishedTodoCount
value.)
Question: So, why does not mobx trigger render()
when unfinishedTodoCount
changes?
Consideration: I am wondering if props.children()
is running asynchronously so mobx cannot catch dereferencing.
(Solutions: Various solutions could be applied by uncommenting lines in the code.)
// Uncomment following so render() will be called when unfinishedTodoCount changes.
//@observer
class LoadContent extends React.Component {
render() {
console.log("rendering LoadContent");
return (
<div>
{this.props.children({
// ...this.props,
})}
</div>
);
}
}
@observer
class TodoListView extends React.Component {
constructor(props) {
super(props);
this.state = {
triggerRender: false
};
}
render() {
console.log("rendering TodoListView");
// Uncomment following so render() will be called when unfinishedTodoCount changes.
//let todoCount = this.props.todoList.unfinishedTodoCount;
//console.log(todoCount);
return (
<div>
<input
type="Button"
onClick={() =>
this.setState({ triggerRender: !this.state.triggerRender })
}
value="Trigger rendering"
/>
<ul>
{this.props.todoList.todos.map((todo) => (
<TodoView todo={todo} key={todo.id} />
))}
</ul>
<div>
{/* Uncomment following so render() will be called when unfinishedTodoCount changes. */
/* {(() => (
<div>Tasks left: {this.props.todoList.unfinishedTodoCount}</div>
))()} */}
<LoadContent>
{() => (
<div>Tasks left: {this.props.todoList.unfinishedTodoCount}</div>
)}
</LoadContent>
</div>
</div>
);
}
}
Complete source code here;
https://codesandbox.io/s/simple-mobx-todolist-forked-hep3t?file=/index.js
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…