我尝试做Store objet UserStore.js
import { observable, action } from 'mobx';
class UserStore {
constructor() {
const me = observable({
me: null,
auth: action.bound(function(me) {
this.me = me;
})
})
}
}
export default UserStore;
在此之后,我这样做
App.js
const App = inject('routing','UserStore')(observer(class App extends Component {
constructor(props, context) {
super(props, context);
this.handleFiles = this.handleFiles.bind(this);
this.prepareTable = this.prepareTable.bind(this);
this.state = {excel: null};
}
render() {
const {location, push, goBack} = this.props.routing;
const {userStore} = this.props.userStore;
在index.js中我做
const stores = {
// Key can be whatever you want
routing: routingStore,
UserStores
};
const history = syncHistoryWithStore(browserHistory, routingStore);
ReactDOM.render(
<Provider {...stores}>
<Router history={history}>
<Entry/>
</Router>
</Provider>,
document.getElementById('root')
);
让我们在所有这些之后尝试打开localhost:3000并查看此错误
错误:MobX观察者:商店'UserStore'不可用!确保它由某些提供商提供
更新: 我用create-react-app创建了一个项目,我不能在代码中使用@(@injector的例子)
答案 0 :(得分:0)
我认为您应该返回商店的一个实例。 为了更有条理,我有一个文件“ storeInitializer.ts”(在此处使用打字稿):
import YourStoreName from '../yourStoreFolder/yourStore';
export default function initializeStores() {
return {
yourStoreName: new YourStoreName(),
}
}
然后我有另一个文件,例如“ storeIdentifier.ts”:
export default class Stores {
static YourStoreName: string = 'yourStoreName';
}
在应用程序文件中,我执行以下操作:
import React from 'react';
import { inject, observer } from 'mobx-react';
import Stores from './storeIdentifier';
const App = inject(Stores.YourStoreName)(observer(props: any) => {
//code here
});
export default App;
或者如果您使用类组件方法...
import React from 'react';
import { inject, observer } from 'mobx-react';
@inject(Stores.YourStoreName)
@observable
class App extends Component {
//code here
}
export default App;