React + mobx

一、安裝 mobx mobx-react

npm install mobx --save

npm install mobx-react --save

二、寫一個(gè)store文件

observable: 觀察對(duì)應(yīng)的數(shù)據(jù)

import { observable } from "mobx";

class TodoList {

? // 利用

?@observable todos = []

}

?

export default new TodoList()

三、在對(duì)應(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ù)了,超級(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的頁面會(huì)根據(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()

我們?cè)赼pp添加一個(gè)btn

<button onClick={() => this.props.todoList.push}>點(diǎn)我添</button>

點(diǎn)擊按鈕的時(shí)候,我們可以對(duì)應(yīng)看到文本的長度在發(fā)生改變

六、computeds

計(jì)算一些對(duì)應(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>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容