Mobx 状态管理
下载
yarn add mobx
# react绑定库
yarn add mobx-react
暴露配置文件
先把 git 内容提交了。
git add .
git commit -m 'eject弹出配置文件之前的文件版本'
然后使用 eject 命令把配置文件暴露出来
yarn run eject
执行命令时会提示这个操作是不可返回的,问我们是否确认。
使用装饰器
react 默认时是不支持装饰器的,所以我们需要把开发环境设置为支持装饰器函数。
找到项目根目录下的 package.json
"babel": {
"plugins":[
[
"@babel/plugin-proposal-decorators",
{
"legacy":true
}
],
[
"@babel/plugin-proposal-class-properties",
{
"loose":true
}
]
],
"presets":[
"react-app"
]
}
todolist示例
结构目录
src/
App.js
todolist/
index.js
inp/
index.js
list/
index.js
store/
store.js
在 store.js 文件中,把需要用到的数据定义出来。
import {
observable } from "mobx";
// 使用observable观察store对象的todos(需要先观察数据,那么别人修改数据时,系统才能得到回馈)
class Store {
@observable todos = [];
del = (item)=>{
this.todos = this.todos.filter(obj=><