跟踪父组件的ViewStore中的状态更改

问题描述 投票:1回答:1

我有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]

reactjs mobx mobx-react
1个回答
1
投票

你可以在autorun的构造函数中使用ChildViewStore来在每次a实例中的ParentViewStore更改时运行一些自定义逻辑。

class ChildViewStore{
    constructor(props){
        autorun(() => {
            console.log(`a changed: ${props.parentViewStore.a}`);
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.