Dom*_*fin 5 javascript reactjs mobx mobx-react
从Redux切换到MobX for React后,我开始非常喜欢MobX.这太棒了.
如果在渲染中未使用提供的商店observable,则MobX具有某种行为,它不会更新组件.我认为通常这是一个非常好的行为,只有在实际发生了变化时才会使组件呈现.
但是......我确实遇到过几种我不想要或者需要在渲染方法中使用MobX observable的情况,在这种情况下我this.props.store的MobX存储不会更新.
在这种情况下,作为一种解决方法,我只是在render方法中引用observable,但我认为这不是一个非常干净的方法,我想知道是否有更简洁的方法来做到这一点?
这个组件代码应该更多地解释我正在询问的内容.它是一个基于我在商店中拥有的MobX observable来改变体溢出样式的组件.
/*------------------------------------*\
Imports
\*------------------------------------*/
import React from 'react';
import connectStore from 'script/connect-store';
import addClass from 'dom-helpers/class/addClass';
import removeClass from 'dom-helpers/class/removeClass';
/*------------------------------------*\
Component
\*------------------------------------*/
class Component extends React.Component {
constructor(props) {
super(props);
this.constructor.displayName = 'BodyClassSync';
}
componentDidMount() {
this.checkAndUpdateMuiClass();
}
componentDidUpdate() {
this.checkAndUpdateMuiClass();
}
checkAndUpdateMuiClass() {
// This place is the only place I need latest MobX store...
if (this.props.store.muiOverlay) {
addClass(window.document.body, 'mod-mui-overlay');
}
else {
removeClass(window.document.body, 'mod-mui-overlay');
}
}
render() {
// This is my workaround so the componentDidUpdate will actually fire
// (with latest and updated store)
// when the 'muiOverlay' observable changes in the MobX store
// Is there any cleaner/better way to do this?
this.props.store.muiOverlay;
// This component doesn't and shouldn't render anything
return null;
}
}
/*------------------------------------*\
Export
\*------------------------------------*/
const ComponentWithStore = connectStore(Component);
export default ComponentWithStore;
Run Code Online (Sandbox Code Playgroud)
(注意:我不使用@decorators,我在connectStore函数中使用ES5语法连接商店.如果解决方案也适用于ES5,那将是非常棒的.)
不知道我是如何错过它的,但感谢@Tholle,我重新阅读了 MobX 文档中的“对可观察值做出反应”部分,并发现该reaction助手是最适合我的解决方案。
然而,这reaction是最适合我所遇到的问题的。和助手在功能上非常相似,我可能也可以将它们用于我的用例autorun。when
https://mobx.js.org/refguide/autorun.html
https://mobx.js.org/refguide/when.html
https://mobx.js.org/refguide/reaction.html
这是代码示例,展示了如何reaction为只想快速复制+粘贴的人使用:
componentDidMount(){
this._notificationsReactionDispose = mobx.reaction(
() => this.props.store.notifications,
(notifications, reaction) => {
... the code that runs when "notifications" in my store change
}
);
}
componentWillUnmount() {
this._notificationsReactionDispose();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1008 次 |
| 最近记录: |