一票摇、安裝 mobx mobx-react
npm install mobx --save
npm install mobx-react --save
二私痹、寫一個(gè)store文件
observable: 觀察對應(yīng)的數(shù)據(jù)
import { observable } from "mobx";
class TodoList {
? // 利用
?@observable todos = []
}
?
export default new TodoList()
三搞坝、在對應(yīng)的頁面添加引用
index頁面
import TodoList from './store/TodoList'
?
<App todoList ={TodoList}>
app頁面
?
export default App {
?render() {
? ?<div>todoList的lenth是{this.props.todoList.length}</div>
? }
}
到這里為止你就能拿到store的數(shù)據(jù)了药有,超級簡單臀晃!
四窗轩、頁面跟著store的數(shù)據(jù)改變發(fā)生改變
app.js頁面添加觀察
import { observable } ?from 'mobx-react'
@observable // 給這個(gè)頁面添加observable裝飾器
export default App {
?render() {
? ?<div>todoList的lenth是{this.props.todoList.length}</div>
? }
}
添加了observable的頁面會根據(jù)注入的數(shù)據(jù)發(fā)生改變而重新渲染
五夯秃、Action
這里我們給todoList添加一個(gè)事件
import { observable, action } from "mobx";
class TodoList {
? // 利用
?@observable todos = []
?@action push() {
? ? ?this.todos.push({
? ? ? ? ?id: 1,
? ? ? ? ?name: 'new Task'
? ?? })
? }
}
?
export default new TodoList()
我們在app添加一個(gè)btn
<button onClick={() => this.props.todoList.push}>點(diǎn)我添</button>
點(diǎn)擊按鈕的時(shí)候,我們可以對應(yīng)看到文本的長度在發(fā)生改變
六品姓、computeds
計(jì)算一些對應(yīng)的屬性或數(shù)值
給todoList添一些料
import { observable, action, computed } from "mobx";
class TodoList {
? // 利用
?@observable todos = []
?@action push() {
? ? ?this.todos.push({
? ? ? ? ?id: 1,
? ? ? ? ?name: 'new Task'
? ?? })
? }
?@computed get allIdCount() {
? ? ?return this.todos.reduce(init, item => {
? ? ? ? ?return init+item.id
? ?? }, 0)
? }
}
?
export default new TodoList()
七寝并、在app添加一個(gè)顯示
<div>目前todoList的id總和是:{this.props.todoList.allIdCount}</div>