脚手架 create-react-app
一、装置
//npm yarn 随需要,尽量不要混用,混用有些资源可能会呈现掉包
yarn add mobxyarn add mobx-react// 版本号"mobx": "^6.3.2","mobx-react": "^7.2.0",
二、配置package.json
1.把暗藏的webpack裸露进去,开释之前记得请先提交代码 git commit 一次
yarn run eject
2.装置@babel/plugin-proposal-decorators 插件 必须的
yarn add @babel/plugin-proposal-decorators
3.批改增加 package.json配置 (手动)
"babel": { "plugins": [ ["@babel/plugin-proposal-decorators", {"legacy": true}] ], "presets": [ "react-app" ]}
三、定义mobx的store
1.目录机构(mobx反对多个多个状态模块)
stores
----- auth.js 模块1
----- test.js 模块2
----- index.js 总入口
2.模块 auth.js
// auth.js和test.js 截然不同 展现auth.js做案例// @action.bound 和 @action 区别 https://cn.mobx.js.org/refguide/action.htmlimport { observable, action, computed } from "mobx";import { makeObservable} from "mobx";export class AuthStore { // 定义变量 @observable name = 'zhangsan000'; @observable sex = '男'; @observable userObj = { name: 'zhangsan000', age: 233, token: '12345689' } // 初始化 constructor() { // mobx6版本当前 必须得在初始化加makeObservable makeObservable(this); } // 动作(bound 能够主动绑定this 避免this 指向扭转) @action.bound setName(v) { console.log('触发action'); this.name = v; } @action setUserObj(obj) { this.userObj = obj; } // 计算属性 @computed get titleName(){ return this.name+'___111'; } }
3.定义导出进口index.js
import { AuthStore } from "./auth";import { TestStore } from "./test";export const store = { authStore: new AuthStore(), testStore: new TestStore()};
4.在react 工程入口 导入
import { store } from './store/index';import { Provider} from 'mobx-react';ReactDOM.render( <React.StrictMode> <Provider store = {store}> <App /> </Provider> </React.StrictMode>, document.getElementById('root'));
四、在页面中应用mobx,并且通过action 扭转mobx
import React, { Component, PureComponent } from "react";import { observer, inject } from 'mobx-react';@inject( 'store')@observerclass Index extends PureComponent { constructor(props) { super(props); console.log(this.props); this.state = { }; } render() { const { authStore, testStore } = this.props.store; return ( <div> {authStore.name}/ {testStore.name}/ {authStore.titleName} <br /> <button onClick = { () => { authStore.setName(new Date().getTime()); } }>点击按钮触发action</button> </div> ); }}export default Index;