0

我正在使用 react-router 3,这是我的路线的代码:

export default (
  <Route>
    <Route path="login" component={LoginPage}/>
    <Route path="/" component={App}>
      <IndexRoute component={Dashboard}/>
      <Route path="dashboard" component={Dashboard}/>
      <Route path="form" component={FormPage}/>
      <Route path="table" component={TablePage}/>
      <Route path="*" component={NotFoundPage}/>
    </Route>
  </Route>
);

这是我的主要内容Index.js,其中包括Providerfrom mobx-react

import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import { Provider } from 'mobx-react';
import injectTapEventPlugin from 'react-tap-event-plugin';
require('./favicon.ico');
import './styles.scss';
import 'font-awesome/css/font-awesome.css';
import 'flexboxgrid/css/flexboxgrid.css';
import store from './Store.js';

injectTapEventPlugin();

render(
    <Provider store={store}><Router routes={routes} history={browserHistory} /></Provider>, document.getElementById('app')
);

store.js看起来像这样:

import { autorun, observable } from 'mobx';

class appStore {
    @observable userSession = {
                isUserLogged: false,
                id: 0,
                name: '',
                token: '',
                memberId: 0,
                membershipId: 1000
            }
}

let store = window.store = new appStore;

export default store;

//test
autorun(()=> {
    console.log(JSON.stringify(store.userSession));
})

我已经为我的 react 应用设置了 mobx,autorun可以登录我的商店。然后我Provider在我的路由器周围添加并尝试在我的中记录道具App.js,我根本没有收到我的商店。

我添加@observer了我的App组件并尝试记录我的道具以检查我的商店是否正在传递,但我没有得到它。

有谁知道为什么?提前致谢。

4

1 回答 1

0

首先,您可以在窗口对象 ( window.store) 上使用存储,因此您可以通过子组件中的存储来访问它。但是,我们应该避免使用全局变量!

<Provider>只是充当通过上下文使商店可用的便捷方法。要允许其他组件使用,您可以使用@inject将与 结合使用的装饰器将其<Provider>添加到已装饰的组件道具中。

当您使用模块系统时,您可以简单地import存储到需要它的每个组件中,而不依赖于全局窗口范围或<Provider>.

于 2017-05-11T06:20:46.157 回答