首页 > 解决方案 > 在父组件的 ViewStore 中跟踪状态变化

问题描述

我有 2 个组件:一个ParentComponent呈现一个ChildComponent

父组件有一个ParentViewStore,子组件有ChildViewStore

有没有办法在使用生命周期方法(例如)的情况下跟踪ParentViewStore属性更改?ChildViewStore React.ComponentComponentWillReceiveProps()

示例代码:

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]

标签: reactjsmobxmobx-react

解决方案


每次实例更改时,您都可以autorun在构造函数中使用一个来运行一些自定义逻辑。ChildViewStoreaParentViewStore

例子

class ChildViewStore{
    constructor(props){
        autorun(() => {
            console.log(`a changed: ${props.parentViewStore.a}`);
        });
    }
}

推荐阅读