create-react-appとmobxの実践

2538 ワード

  • アプリケーション作成
  • 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 }]
      ]
    }
    
    
  • 作成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
    
  • 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
  • 非同期関数
  • // /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()}>