[关闭]
@Bios 2018-12-10T08:46:52.000000Z 字数 4047 阅读 805

react-create-app 中使用 Mobx

react mobx


安装配置

  1. yarn add mobx mobx-react
  2. yarn add babel-plugin-transform-decorators-legacy
  1. // webpack.config.dev.js webpack.congif.prod.js
  2. {
  3. test: /\.(js|jsx|mjs)$/,
  4. include: paths.appSrc,
  5. loader: require.resolve('babel-loader'),
  6. options: {
  7. plugins: [ // 就加上这个plugins
  8. ['transform-decorators-legacy']
  9. ],
  10. // This is a feature of `babel-loader` for webpack (not Babel itself).
  11. // It enables caching results in ./node_modules/.cache/babel-loader/
  12. // directory for faster rebuilds.
  13. cacheDirectory: true,
  14. },
  15. },

使用

在 src 文件夹下 新建一个store文件夹

  1. // index.js
  2. import homeStore from './home_store.js';
  3. import otherStore from './others.js';
  4. export {homeStore, otherStore}
  5. // home_store.js
  6. import {observable, action, computed} from 'mobx';
  7. class HomeStore {
  8. @observable text;
  9. @observable num;
  10. constructor() {
  11. this.num = 0
  12. this.text = 'Hello Word!'
  13. }
  14. @action
  15. plus = () => {
  16. this.num = ++this.num
  17. }
  18. minus = () => {
  19. this.num = --this.num
  20. }
  21. change = (str) => {
  22. this.text = str
  23. }
  24. @computed
  25. get plusNum (){
  26. return this.num + 5
  27. }
  28. }
  29. const homeStore = new HomeStore()//通过new 创建一个homeStore对象实例通过export导出
  30. export default homeStore
  31. // others.js
  32. import {observable, action} from 'mobx';
  33. class OthersStore {
  34. @observable str;
  35. constructor() {
  36. this.str = '这个值来自其他模块'
  37. }
  38. @action
  39. getdata = () => {
  40. fetch('api/comments/show?id=4199740256395164&page=1')
  41. .then(res => {res.json().
  42. then(action((data) => {
  43. // console.log(data);
  44. this.str = data.msg;
  45. }))
  46. })
  47. }
  48. }
  49. const otherStore = new OthersStore()//通过new 创建一个homeStore对象实例通过export导出
  50. export default otherStore

在action 中请求数据,用action进行数据绑定

全局注册

  1. // app.js
  2. import React, { Component } from 'react';
  3. import logo from '../../assets/img/logo.svg';
  4. import './index.css';
  5. import {Provider} from "mobx-react";
  6. import * as store from '../../store/index.js'//将所有方法给预一个store的别名方面在不同组件中调用
  7. import Mobx from '../../views/mobx_test.js';
  8. import Mobx2 from '../../views/mobx2.js';
  9. class App extends Component {
  10. render() {
  11. return (
  12. <Provider store={store}>
  13. <div className="App">
  14. <header className="App-header">
  15. <img src={logo} className="App-logo" alt="logo" />
  16. <h1 className="App-title">Welcome to React</h1>
  17. </header>
  18. <p className="App-intro">
  19. To get started, edit <code>src/App.js</code> and save to reload.
  20. </p>
  21. <Mobx></Mobx>
  22. <Mobx2></Mobx2>
  23. </div>
  24. </Provider>
  25. );
  26. }
  27. }
  28. export default App;

组件中使用

  1. // mobx2.js
  2. import React, {Component} from "react";
  3. import {observer,inject} from 'mobx-react';
  4. @inject('store') // 将store注入到当前组件中
  5. @observer // 将该组件变成响应式组件
  6. class Mobx2 extends Component {
  7. handleClick = () => {
  8. this.props.store.otherStore.getdata()
  9. }
  10. render() {
  11. return (
  12. <div>
  13. <h1>体现mobx的响应式</h1>
  14. <h2>homeStore.text: {this.props.store.homeStore.text}</h2>
  15. <h2>homeStore.num: {this.props.store.homeStore.num}</h2>
  16. <button onClick={this.handleClick}> 点击获取数据修改str</button>
  17. </div>
  18. )
  19. }
  20. }
  21. export default Mobx2;
  1. // mobx_test.js
  2. import React, {Component} from "react";
  3. import {observer,inject} from 'mobx-react';
  4. @inject('store') // 将store注入到当前组件中
  5. @observer // 将该组件变成响应式组件
  6. class Mobx extends Component {
  7. handelPlus =() => {
  8. this.props.store.homeStore.plus()
  9. }
  10. handelMinus =() => {
  11. this.props.store.homeStore.minus()
  12. }
  13. handleChange = () => {
  14. this.props.store.homeStore.change('哈哈哈哈,成功!')
  15. }
  16. render() {
  17. return (
  18. <div>
  19. <h1>Mobx Test</h1>
  20. <h2>homeStore.text: {this.props.store.homeStore.text}</h2>
  21. <h2>homeStore.num: {this.props.store.homeStore.num}</h2>
  22. <h3>otherStore.str: {this.props.store.otherStore.str}</h3>
  23. <h3>homeStore.computed: {this.props.store.homeStore.plusNum}</h3>
  24. 调用action:
  25. <br/>
  26. <button onClick={this.handelMinus}>减</button>
  27. <button onClick={this.handelPlus}>加</button>
  28. <button onClick={this.handleChange}>改变 homeStore.text</button>
  29. </div>
  30. )
  31. }
  32. }
  33. export default Mobx;

组件中使用时要注意 this 的问题,推荐使用箭头函数

另外一种只作为数据与视图的隔离

不做全局绑定 也没有响应

  1. // store/good.js
  2. import { observable, action } from 'mobx';
  3. import { httpReq } from '../api/httpReq.js';
  4. export default class GoodsModel {
  5. @observable goodsList = [];
  6. @action
  7. getGoodsList = async (id) => {
  8. const url = 'http://dev.xyf.78dk.com/v5/firstproductlists';
  9. const method = 'post';
  10. const params = {
  11. merchantId: id || 1005
  12. }
  13. const responseData = await httpReq({url, method, params}).then(res => res.json());
  14. this.goodsList = [].concat(responseData.data.productList);
  15. }
  16. }
  17. // view/good.js
  18. import React, { Component } from 'react';
  19. import {observer} from 'mobx-react';
  20. @observer
  21. export default class Goods extends Component{
  22. // new数据实例
  23. goodsModel = new GoodsModel();
  24. getProductList(){
  25. // 调用实例方法
  26. this.goodsModel.getGoodsList();
  27. }
  28. render() {
  29. // 拿取数据
  30. const { goodsList } = this.goodsModel;
  31. return (
  32. <div>
  33. {goodsList}
  34. </div>
  35. );
  36. }
  37. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注