我有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]
答案 0 :(得分:1)
每次ChildViewStore
实例中的a
被更改时,您可以在ParentViewStore
的构造函数中使用autorun
来运行一些自定义逻辑。
示例
class ChildViewStore{
constructor(props){
autorun(() => {
console.log(`a changed: ${props.parentViewStore.a}`);
});
}
}