4
头图

最近我用create-react-app搭建项目,安装了mobx@6.xmobx-react@6.x,写一个使用store例子时发现依赖store的组件没有重新渲染。

示例:

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

class TestStore {
  @observable count = 0;

  @action
  setValue = <T extends keyof CountStore>(key: T, value: this[T]) => {
    this[key] = value;
  }
}

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));

image

我们可以看到storecount数值是有变化的,但是组件并没有重新渲染,而且控制台也没有报错。在思考之际,我想到与之前项目库版本做对比,将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)

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

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

import { makeAutoObservable  } from 'mobx';

class TestStore {

  constructor() {
    makeAutoObservable(this);
  }

  count = 0;

  setValue = <T extends keyof CountStore>(key: T, value: this[T]) => {
    this[key] = value;
  }

}

export default {
    testStore: new TestStore()
}

记得要微笑
1.9k 声望4.5k 粉丝

知不足而奋进,望远山而前行,卯足劲,不减热爱。


引用和评论

0 条评论