reactjs 如何观察React组件中的存储值?

o8x7eapl  于 2023-04-20  发布在  React
关注(0)|答案(1)|浏览(121)

我有一个商店,让我们命名它- 'myStore'
myStore.jsx

@observer
class myStore {
@observable public varToObserve;
...... rest of the logic
}

我有上述存储的另一个 Package 器,让我们称之为- myStoreWrapper.js

class myStoreWrapper {
myStore = globalStore.get('myStore');
} export default new myStoreWrapper();

我不能直接访问myStore,只能访问myStoreWrapper,我想观察varToObserve变量。正确的方法是什么?
方法A:

@observer
class myClass {

logic() {
    return myStoreWrapper.myStore.varToObserve;
}
render(){
    <myComponent myProp={this.logic()}
}
}

方法B:

@observer
class myClass {
@observable varToObserve = myStoreWrapper.myStore.varToObserve;

@computed
logic() {
    return this.varToObserve;
}
render(){
    <myComponent myProp={this.logic()}
}
}
2uluyalo

2uluyalo1#

我会说这基本上是相同的。你不需要单独创建@observable varToObserve并重新分配它,因为myStore.varToObserve已经是一个observable,只需在方法中直接使用它:

// Depends on what you want to do inside of `logic` method.
// You can make it `computed` if you want to cache the output, derive some info from your observable and etc
@computed
logic() {
    // whatever logic you have
    return myStoreWrapper.myStore.varToObserve;
}

相关问题