mobx4.x/5.x 与 mobx6.x 区别

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

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

// [email protected]
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 (
    
{testStore?.count}
); } export default inject('testStore')(observer(App));

mobx4.x/5.x 与 mobx6.x 区别_第1张图片

我们可以看到store中count数值是有变化的,但是组件并没有重新渲染,而且控制台也没有报错。在思考之际,我想到与之前项目库版本做对比,将mobx换成[email protected]版本,发现可以解决这个问题,那么这两个版本有什么不一样吗?我们需看看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 }) => (
    
))

ReactDOM.render(, 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()
}

你可能感兴趣的:(mobx,版本)