【发布时间】:2019-12-26 15:04:54
【问题描述】:
我正在尝试学习如何将 MobX 与 React 一起使用,但我不明白为什么需要使用 Provider 或 Context,如果持有状态的对象永远不会改变,只会改变它的内容。
例如我在 store.js 中有一个商店(一个随时间变化的简单计时器):
import { decorate, observable, action } from 'mobx';
import React from 'react';
class TheTimer {
currentTick = 0; // In seconds since start
tick = () => {
this.currentTick = Math.floor(performance.now() / 1000);
}
}
decorate(TheTimer, {
currentTick: observable,
tick: action
});
// Bare store
export const timerStore = new TheTimer();
// Store as React context
export const TimerStoreContext = React.createContext(timerStore);
// This makes the timer go
setInterval(timerStore.tick, 100);
现在在组件中使用裸存储已经没有问题了:
import React from 'react';
import { configure } from 'mobx';
import { observer } from 'mobx-react';
import { timerStore } from './store';
configure({ enforceActions: 'observed' });
const App = observer(() => {
return (
<p>{timerStore.currentTick}</p>
);
});
export default App;
使用上下文也可以:
import React from 'react';
import { configure } from 'mobx';
import { observer } from 'mobx-react';
import { TimerStoreContext } from './store';
configure({ enforceActions: 'observed' });
const App = observer(() => {
const timerStore = React.useContext(TimerStoreContext);
return (
<p>{timerStore.currentTick}</p>
);
});
export default App;
(我使用的是 create-react-app 加 mobx,mobx-react,即 React 16.9.0 与 MobX 5.13.0 和 mobx-react 6.1.3)
请注意,商店只创建一次,从那时起,它始终保持同一个对象。
为什么在将 store 直接用作全局变量时,每个人(或旧的基于 mobx-react Provider 的解决方案)都使用 Context 也有效?
仅仅是可测试性吗?
请注意,我也有不是 React 的 JS 代码,应用程序通过 Websockets 与服务器通信,来自服务器的更新也会导致调用动作;我计划为此使用裸存储,因为该代码位于 React 组件之外。
【问题讨论】:
标签: reactjs mobx mobx-react