搭建一个简单的react+mobx应用

import React from 'react'
import { render } from 'react-dom'
import { observable, computed } from 'mobx'
import { observer } from 'mobx-react'


class Todo {
  id = Math.random()
  @observable title
  @observable finished = false
  constructor(title) {
    this.title = title
  }
}

class TodoList {
  @observable todos = []
  @computed get unfinishedTodoCount() {
    return this.todos.filter(todo => !todo.finished).length
  }

}

const TodoView = props => {
  return (
    
  • {props.todo.finished = !props.todo.finished}}/>{props.todo.title}
  • ) } const TodoListView = observer(props => { return (
      { props.todoList.todos.map(todo => ) }
    Task left: {props.todoList.unfinishedTodoCount}
    ) }) const store = new TodoList() store.todos.push( new Todo("Get Coffee"), new Todo("Write simpler code") ) const App = props => { return ( ) } render(, document.getElementById('app'))

    以上有几点需要注意:

    1. @observer只能用在类组件前面,在函数组件前使用会报Leading decorators must be attached to a class declaration
    2. 装饰器语法处于实验室语法,目前浏览器还不支持,当在项目中使用时会报对修饰器的实验支持是一项将在将来版本中更改的功能。设置 "experimentalDecorators" 选项以删除此警告。在项目->首选项->设置中搜索experimentalDecorators,关闭对修饰器校验。
      搭建一个简单的react+mobx应用_第1张图片
      上面处理仅仅使vscode支持修饰器语法,但打包时babel并不支持,会报Support for the experimental syntax 'decorators-legacy' isn't currently enabled。我们需要安装@babel/plugin-proposal-decorators,然后在plugins中加上["@babel/plugin-proposal-decorators", { "legacy": true }]
    3. 在打包时还会报Support for the experimental syntax 'classProperties' isn't currently enabled,这是因为babel不支持类属性语法,因此需要安装@babel/plugin-proposal-class-properties并在plugins中配置["@babel/plugin-proposal-class-properties", { "loose": true }]

    整个.babelrc配置如下:

    {
      "presets": ["@babel/preset-env", "@babel/preset-react"],
      "plugins": [
        "@babel/plugin-transform-runtime",
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
        ["@babel/plugin-proposal-class-properties", { "loose": true }]
      ]
    }
    

    打包后运行结果:
    搭建一个简单的react+mobx应用_第2张图片

    你可能感兴趣的:(mobx,react.js)