我有2个组成部分:ParentComponent
呈现ChildComponent
父组件有ParentViewStore
,子组件有ChildViewStore
,
有没有办法在不使用ParentViewStore
生命周期方法(例如ChildViewStore
)的情况下跟踪React.Component
中的ComponentWillReceiveProps()
属性变化?
示例代码:
class ParentViewStore{
@observable a;
}
class ChildViewStore{
/*
code to run when
ParentViewStore.a
changes
*/
}
ChildViewStore
构造函数中的代码只运行一次,后续的重新渲染不会再次触发构造函数。 ParentViewStore
作为支柱传递给ChildViewStore
我尝试过的:
class ChildViewStore{
@observable parentProperty;
constructor(props){
this.parentProperty = props.parentViewStore.parentProperty
observe(this.parentProperty, (change) => {
console.log("change")
});
}
}
但这会引发[mobx] Cannot obtain administration from [parentPropertyValue]
你可以在autorun
的构造函数中使用ChildViewStore
来在每次a
实例中的ParentViewStore
更改时运行一些自定义逻辑。
例
class ChildViewStore{
constructor(props){
autorun(() => {
console.log(`a changed: ${props.parentViewStore.a}`);
});
}
}