test.md# 主要內容css
爲了以後項目的拓展性,將全部的數據集中放在 store/
目錄下。如今項目結構以下:react
src/
App.js
App.css
index.js
conponents/
(some components)
containers/
(some containers)
stores/
(some stores)
複製代碼
先看一下如何組織 store。目前是按照功能來組織,如今只開發了記分功能,因此只有一個 scoreStore
,後續還會有 userStore
來管理和用戶登陸相關的數據,等等。git
在 scoreStore.js
中定義了以下 observable 和 action:github
import { observable, action } from 'mobx';
class ScoreStore {
// 數據
@observable score = 0;
// 方法
@action setScore (score) {
this.score = score
}
}
export default new ScoreStore();
複製代碼
在 HomePage
中使用則須要在前面 inject 這個 store,並加上 observer 修飾:架構
// HomePage.js
// 一系列導入中加上 mobx-react 相關
import { inject, observer } from "mobx-react";
@inject ("scoreStore")
@observer
class HomePage extends Component {
// 一些代碼…
// 訪問 scoreStore 的數據或方法時時使用 this.props
this.props.scoreStore.setScore(score);
// 更多代碼…
}
複製代碼
其餘須要訪問數據的組件也同理作修改,這樣,在修改數據的時候,全局都會相應變化了。app
github.com/gothinkster… 主要參考了 store 的結構。post
React + MobX + Electron + Node.js + MongoDB 全棧項目開發實踐(零)前言this
React + MobX + Electron + Node.js + MongoDB 全棧項目開發實踐(一)spa
React + MobX + Electron + Node.js + MongoDB 全棧項目開發實踐(二)容許 decorator3d