【发布时间】:2018-09-10 08:57:39
【问题描述】:
我正在尝试将一个 mobX 商店传递到另一家商店,以下是我的商店代码:
商店类 1:
export default class APIKeyStore
{
@persist @observable apiKey = '****';
}
存储类 2:
export default class ServiceCalls
{
@persist @observable apiKeysStore;
constructor(apiStore)
{
this.apiKeysStore = apiStore;
console.log('constructor', this.apiKeysStore.apiKey);
}
@action async initializeApp()
{
console.log('initializeApp', this.apiKeyStore.apiKey);
}
}
index.js:
import APIKeyStore from './models/APIKeyStore';
import ServiceCalls from './models/ServiceCalls';
const serviceCalls = new ServiceCalls(new APIKeyStore())
const stores = {
serviceCalls: serviceCalls
}
export default
{
...stores
};
我在其中调用 store 2 的 initializeApp() 方法的组件文件:
@inject('serviceCalls')
@observer
class ZeroStepScreen extends Component
{
async componentWillMount()
{
try
{
console.log('componentWillMount', this.props.serviceCalls.apiKeysStore.apiKey);
await this.props.serviceCalls.initializeApp();
}
catch(e)
{
console.log(e);
}
}
}
在上面的类中,我有三个 console.log(..) 声明 - 它从第二个商店的 constructor 和组件的 componentWillMount() 方法报告正确的结果。
当调用相同的第二个存储类'initializeApp() 方法时,this.apiKeysStore.apiKey 总是抛出我无法读取未定义的属性。
第二类的构造函数 - console.log(this.apiKeysStore.apiKey) - 好的
ZeroStepScreen - console.log(this.props.serviceCalls.apiKeysStore.apiKey) - 好的
第二类'initializeApp() - console.log(this.apiKeysStore.apiKey) - 错误
我无法理解我做错了什么,第二个商店类在访问 this.apiKeysStore.apiKey 时得到未定义,而其构造函数报告正确,组件类报告正确。
【问题讨论】:
标签: react-native mobx mobx-react mobx-persist