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 = () => (
  
    
  
)

ReactDOM.render(, 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 (
      
{this.props.TodoList.list.map((v, k) => (

{v}

))}

this.props.TodoList.addList()}> {this.props.TodoList.todoSize}

) } } 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

this.props.TodoList.reqList()}>获取数据

你可能感兴趣的:(create-react-app 和 mobx 实践)