mobx5相比较mobx4的区别

转载【原文地址找不到了】
最近我用 create-react-app 搭建 react typescript 项目,安装了最新版本 mobx 和 mobx-react,再写一个 store 例子时发现组件依赖的 store 数值有变化但组件没有重新渲染,下面我们来看是什么原因导致的。

我们先照平时方式来编写 store

// mobx@6.0.1
import { action, observable } from 'mobx';

class TestStore {
  @observable count = 0;

  @action
  setValue = (key: keyof TestStore, value: any) => {
    console.log(key, value);
    this[key] = value as never;
  }
}

export default {
  testStore: new TestStore()
}

页面引入

import { inject, observer } from 'mobx-react';
import React from 'react';

enum Oprate {
  MINUS = 'MINUS',
  PLUS = 'PLUS'
}

function App(props: any) {

  const {testStore} = props;

  const oprate = (type: Oprate) => {
    switch (type) {
      case Oprate.MINUS:
        testStore.setValue('count', testStore.count - 1);
        break;
      case Oprate.PLUS:
        testStore.setValue('count', testStore.count + 1);
        break;
      default:
        break;
    }
  }

  return (
    <div>
      <button onClick={() => oprate(Oprate.MINUS)}>--</button>
      <span>{testStore?.count}</span>
      <button onClick={() => oprate(Oprate.PLUS)}>++</button>
    </div>
  );
}

export default inject('testStore')(observer(App));

img

我们可以看到 store 中 count 数值是有变化的,但是组件并没有重新渲染,而且控制台也没有报错。在思考之际,我想到与之前项目库版本做对比,将 mobx 换成mobx@4.6.0版本,发现可以解决这个问题,那么这两个版本有什么不一样吗?我们需看看 mobx GitHub 官网

发现 store 的写法已经改变,官网例子如下:

import React from "react";
import ReactDOM from "react-dom";
import { makeAutoObservable } from "mobx";
import { observer } from "mobx-react";

// Model the application state.
class Timer {
  secondsPassed = 0;

  constructor() {
    makeAutoObservable(this);
  }

  increase() {
    this.secondsPassed += 1;
  }

  reset() {
    this.secondsPassed = 0;
  }
}

const myTimer = new Timer();

// Build a "user interface" that uses the observable state.
const TimerView = observer(({ timer }) => (
  <button onClick={() => timer.reset()}>
    Seconds passed: {timer.secondsPassed}
  </button>
));

ReactDOM.render(<TimerView timer={myTimer} />, document.body);

// Update the 'Seconds passed: X' text every second.
setInterval(() => {
  myTimer.increase();
}, 1000);

无需通过 observable 和 action 等修饰器,直接在构造函数中使用 makeAutoObservable 来实现 observable 和 action 修饰器功能,使代码更加简洁。

将上面例子改写一下就可以了


import { makeAutoObservable  } from 'mobx';

class TestStore {

  constructor() {
    makeAutoObservable(this);
  }

  count = 0;

  setValue = (key: keyof TestStore, value: any) => {
    this[key] = value;
  }

}

export default {
    testStore: new TestStore()
}
原文地址:https://www.cnblogs.com/xiaozhumaopao/p/14422260.html