【问题标题】:react-mobx - store displayed as a function instead of returning valuereact-mobx - 存储显示为函数而不是返回值
【发布时间】:2017-04-17 09:56:59
【问题描述】:

我正在尝试将 mobx 添加到现有项目中。该项目由 create-react 应用程序引导,弹出,然后我在其上添加了 mobx。到目前为止,这是我的商店:

从“mobx”导入{observable, action, computed}

export default class timerStore {
    @observable message = 'THIS IS FROM THE STORE'

    constructor(count, message) {
        this.message = message;
    }

}

我在索引组件中将商店传递给我的应用程序:

render(
  (<Provider timerStore={timerStore}>
      <Router history={hashHistory}>
        <Route component={Main} path="/">
          <IndexRoute component={Tea}/>
          <Route component={About} path="/about"/>
          <Route component={Timer} path="/timer"/>
        </Route>
      </Router>
    </Provider>
  ),
  document.querySelector('#root')
);

然后我尝试在 Timer 组件中引用它:

@inject("timerStore")
@observer
class Timer extends Component {

    render() {
        const { message } = this.props.timerStore

        return(
            <div className="content-card timer-card">
                <h1 className="title">Tea timer {message}</h1>
            </div>
        )
    }
}

export default Timer;

但是消息字符串没有显示出来,当我在调试器(this.props.timerStore.message)中检查它时,它显示为未定义。

它还将this.props.timerStore 显示为以countmessage 作为参数的函数。

我做错了什么?

我清除了大部分应用程序逻辑以保持示例简单。如果此处缺少任何需要帮助的信息,请告诉我,我会更新问题。

【问题讨论】:

    标签: javascript reactjs ecmascript-6 mobx-react


    【解决方案1】:

    应用启动时基本忘记创建新商店了。所以这现在是我的 index.js:

    import React from 'react';
    import {render} from 'react-dom';
    import {hashHistory, Router, Route, IndexRoute} from 'react-router';
    
    import { Provider } from 'mobx-react';
    import timerStore from './Stores/timerStore';
    
    import './reset.css';
    
    import Main from './Main/Main.component';
    import Tea from './Tea/Tea.component';
    import About from './About/About.component';
    import Timer from './Timer/Timer.component';
    
    const store = new timerStore()
    
    render(
      (<Provider timerStore={store}>
          <Router history={hashHistory}>
            <Route component={Main} path="/">
              <IndexRoute component={Tea}/>
              <Route component={About} path="/about"/>
              <Route component={Timer} path="/timer"/>
            </Route>
          </Router>
        </Provider>
      ),
      document.querySelector('#root')
    );
    

    【讨论】:

      猜你喜欢
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      相关资源
      最近更新 更多