mobx @inject没有创建新的(装饰的)组件

时间:2018-11-30 16:27:35

标签: javascript reactjs mobx mobx-react

我正在尝试使用mobx设置React应用程序进行状态管理。

我已经定义了这样的商店:

  

ApplicationStore.js

import { observable, action, reaction } from 'mobx';

class ApplicationStore {

  @observable appName = 'App';
  @observable currentRoute = '/';
  @observable appLoaded = false;

  @action setAppLoaded() {
      this.appLoaded = true;
  }
}

export default new ApplicationStore();

Root.js中使用它来收集存储/调试工具,并将其传递给主要的App组件:

  

Root.js

import React, { Component } from 'react';

import { Provider } from 'mobx-react';

import App from './App.js';

import './Root.css';

import ApplicationStore from './stores/ApplicationStore';

const stores = { ApplicationStore }

class Root extends Component {
  render() {
    return (
      <Provider {...stores}>
        <App />
      </Provider>
    );
  }
}

export default Root;
  

App.js

import React, { Component } from 'react';

import Login from './views/login/Login'
import Dashboard from './views/dashboard/Dashboard'

import { observer, inject } from 'mobx-react';

import { Switch, Route, BrowserRouter, Redirect } from 'react-router-dom'

@inject('ApplicationStore')
@observer
class App extends Component {

    componentDidMount() {
        console.log(this.props)
    };

   render() {

    var loggedIn = false;        

    return (
      <div className="App">
        <BrowserRouter>
          <Switch>
            <Route exact path="/" render={() => (
              loggedIn ? (
                <Redirect to="/dashboard" />
              ) : (
                <Redirect to="/login" />
              )
              )} />
            <Route exact path="/login" component={Login} />
            <Route exact path="/dashboard" component={Dashboard} />
          </Switch>
        </BrowserRouter>
      </div>
    );
  }
}

export default App;

console.log(this.props)中的componentDidMount()表明道具是空的。

不仅如此,在React-dev-tools中检查<Provider>的子项表明@inject并没有创建新的组件(它显示<App>而不是预期的{{ 1}}。

我不了解和

1 个答案:

答案 0 :(得分:1)

问题出在babel配置上。我正在使用@Alex Sherman方法向react-app-rewired which can be seen here...

添加装饰器功能

create-react-app文件中,我有:

config-overrides.js

我将其更改为:

const { injectBabelPlugin } = require("react-app-rewired");

module.exports = function override(config, env) {

    config = injectBabelPlugin(['@babel/plugin-proposal-decorators', {decoratorsBeforeExport: false}], config);

    return config;
} 

它现在按预期工作。