- 创建应用
sudo create-react-app react-mobx-app
cd react-mobx-app && yarn eject
- 安装
mobx和mobx-react
yarn add mobx mobx-react
- 配置装饰器
decorator
yarn add @babel/plugin-proposal-decorators -D
# package.json 配置babel
{
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose" : true }]
]
}
- 编写
mobxstore
新建src/stores文件夹
创建src/stores/TodoList.js文件
import { observable, action, computed } from 'mobx'
class TodoList {
@observable list = [1, 2, 3]
// 添加条数
@action addList = item => {
this.list.push(item)
}
// 删除指定条数
@action remove = idx => {
this.list.splice(idx, 1)
}
// 计算属性 计算 list.size
@computed
get todoSize() {
return this.list.length
}
}
const store = new TodoList()
export default store
-
App连接store
// src/index.js 把 store 加入 app
import { Provider } from 'mobx-react'
import TodoList from './stores/TodoList'
const Root = () => (
<Provider TodoList={TodoList}>
<App />
</Provider>
)
ReactDOM.render(<Root />, document.getElementById('root'))
// view .jsx 获取store 数据
import React from 'react'
import { observer, inject } from 'mobx-react'
@inject('TodoList') // 相当于 connect
@observer // 包装成订阅者
class TodoView extends React.Component {
render() {
console.log(this.props.TodoList)
// TodoList {addList: f, remove: f,todoSize:3 ,list: proxy}
return (
<div>
{this.props.TodoList.list.map((v, k) => (
<p key={k}>{v}</p>
))}
<h2 onClick={e => this.props.TodoList.addList()}>
{this.props.TodoList.todoSize}
</h2>
</div>
)
}
}
export default TodoView
- 异步函数
// /src/store/TodoList.js
@action
reqList = async ()=>{
fetch('/weather/common?source=xw&weather_type=forecast_1h|forecast_24h|index|alarm|limit|tips&province=%E5%9B%9B%E5%B7%9D&city=%E6%88%90%E9%83%BD')
.then(res=>res.json())
.then(res=>{
console.log(res)
this.list = _.reverse(this.list)
})
}
// view
<p onClick={e=>this.props.TodoList.reqList()}>获取数据</p>











网友评论