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 (
    <li>
      <input type="checkbox" checked={props.todo.finished} onClick={() => {props.todo.finished = !props.todo.finished}}/>{props.todo.title}
    </li>
  )
}

const TodoListView = observer(props => {
  return (
    <div>
      <ul>
        {
          props.todoList.todos.map(todo => <TodoView key={todo.id} todo={todo}></TodoView>)
        }
      </ul>
      Task left: {props.todoList.unfinishedTodoCount}
    </div>
  )
})

const store = new TodoList()
store.todos.push(
  new Todo("Get Coffee"),
  new Todo("Write simpler code")
)

const App = props => {
  return (
    <TodoListView todoList={store}/>
  )
}

render(<App store={store}/>, document.getElementById('app'))

以上有几点需要注意:

  1. @observer只能用在类组件前面,在函数组件前使用会报Leading decorators must be attached to a class declaration
  2. 装饰器语法处于实验室语法,目前浏览器还不支持,当在项目中使用时会报对修饰器的实验支持是一项将在将来版本中更改的功能。设置 "experimentalDecorators" 选项以删除此警告。在项目->首选项->设置中搜索experimentalDecorators,关闭对修饰器校验。
    image.png
    上面处理仅仅使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 }]
  ]
}

打包后运行结果:
mobx-demo.gif


记得要微笑
1.9k 声望4.5k 粉丝

知不足而奋进,望远山而前行,卯足劲,不减热爱。