跟踪父组件 ViewStore 中的状态变化
Tracking state changes in ViewStore of a parent component
我有 2 个组件:ParentComponent
呈现 ChildComponent
父组件有 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]
每次 ParentViewStore
实例中的 a
更改时,您可以在 ChildViewStore
的构造函数中使用 autorun
来 运行 一些自定义逻辑。
例子
class ChildViewStore{
constructor(props){
autorun(() => {
console.log(`a changed: ${props.parentViewStore.a}`);
});
}
}
我有 2 个组件:ParentComponent
呈现 ChildComponent
父组件有 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]
每次 ParentViewStore
实例中的 a
更改时,您可以在 ChildViewStore
的构造函数中使用 autorun
来 运行 一些自定义逻辑。
例子
class ChildViewStore{
constructor(props){
autorun(() => {
console.log(`a changed: ${props.parentViewStore.a}`);
});
}
}