create-react-app 和 mobx 实践

  1. 创建应用
sudo create-react-app react-mobx-app
cd react-mobx-app && yarn eject
  1. 安装mobxmobx-react
yarn add mobx mobx-react
  1. 配置装饰器 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 }]
  ]
}

  1. 编写mobx store

新建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
  1. 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
  1. 异步函数
// /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>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容