背景:
发现在mobx中似乎深层次的数据变动有时候不会触发新的render, 例子如下:
// 在store中
class SpaceStore {
@observable treeData = {
id: 100,
name: 'test',
children: []
};
}
//在组件中
const store = new SpcaceStore();
class Space extends Component {
componentDidMount(){
console.log('componentDidMount')
store.treeData.name = 'hehe';
}
...
render(){
console.log('this is render');
//第一种情况,打印整个treeData(需要注释第二种情况)
console.log(store.treeData)
//第二种情况,打印treeData中的name(需要注释注释第一中情况)
console.log(store.treeData.name)
//第三种,解除前两条的注释
return (
<div>test</div>
);
}
}
this is render
Object
componentDidMount
可以奇怪的地方在于,打印的Object代表是treeData,这是在name改变前打印的,可是奇怪的是其name值已经变成了'hehe'
this is render
test
componentDidMount
this is render
hehe
仅仅是打印store.treeData.name, 居然能触发第二次render, 并且打印的name值前后变化都是正确的
...
console.log('this is render');
console.log(store.treeData)
console.log(store.treeData.name)
...
打印的结果以及顺序如下:
this is render
test
Object(其中name指为hehe)
componentDidMount
this is render
Object(其中name值为hehe)
hehe
奇怪的地方在于两次打印的treeData值中的name值都是改变后,这好奇怪