eact脚手架 - Mobx项目创建及配置
1.创建项目
$npx create-react-app project
2.进入项目
$ cd app
3.进行配置文件抽离
$ yarn eject
4.启动项目
$ yarn start
5.配置文件抽离以后可能导致项目启动失败
-
出现报错 :Build fails after eject: Cannot find module ‘@babel/plugin-transform-react-jsx’
-
解决方法
1.删除 node_modules 文件夹 2.运行 yarn 3.重新 yarn start
6.安装mobx mobx-react
$ yarn add mobx mobx-react;
mobx 是状态管理工具
mobx-react 是做数据分片和数据获取
-
注意: 如果git冲突
-
解决: 我们要原文件先放到本地暂存盘
git add .
git commit -m ’ -
然后 : 安装mobx mobx-react’
-
注意不要git push
7.配置装饰器( 修饰器 es6 ) babel,依次执行下列命令
* yarn add babel-plugin-transform-decorators-legacy -D
* yarn add @babel/preset-env -D
* yarn add babel-plugin-transform-class-properties -D
* yarn add @babel/plugin-proposal-decorators -D
8.配置package.json
"babel": {
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"transform-class-properties"
],
"presets": [
"react-app",
"@babel/preset-env"
]
},
/*
注意: 以下两个配置顺序不可更改
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"transform-class-properties"
*/
项目中使用mobx流程
1、新建store文件夹
建立一个index.js文件作为store模块
2、在整个项目的入口文件,使用Provider模块,将store作为属性值传递给后代
import store from './store/index'
import { Provider } from 'mobx-react';
ReactDOM.render(
<Provider store = { store } >
<App />
</Provider>
, document.getElementById('root'));
3、打造mobx数据包,在store文件夹下,建立子数据包文件夹,在子文件夹内建立index.js文件,作为数据包模块
//store/count/index.js文件,打造mobx分片数据包
import { observable,action,computed } from 'mobx'
class Count{
@observable
count = 0
@action
//action是用户操作
increment () {
console.log( 'action' )
// 修改数据
console.log( this )
// this.count ++
this.props.store.count.count ++
}
@computed
// 方法 , 当数据改变时,它会自动执行
get newCount () {
return this.count *= 2
}
}
const count = new Count()
export default count
4.组件的使用
哪个组件使用 , 就在哪个组件中 “注入” inject
import {inject} from 'mobx-react'
@inject('store')
import React, { Component } from 'react';
import { inject,observer } from 'mobx-react'
@inject('store') // 将store中的数据注入当前组件
@observer
class Content extends Component{
render () {
return (
<div>
{/* 在action中进行数据操作的时候,this的指向会丢失,在此将this的指向修改指向组件 */}
<button onClick = { this.props.store.count.increment.bind( this ) }> + </button>
<p> count: { this.props.store.count.count }</p>
</div>
)
}
}
export default Content
5、组件内使用数据
this.props.store.xxx 可以拿到数据
注意:
- this.porps里面没有找到 @action 装饰器定义的方法, 但是可以直接使用,
- this会丢失
- this.props.store.count.increment.bind(this)