轉載【原文地址找不到了】
最近我用 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));
我們可以看到 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()
}