【发布时间】:2018-05-03 02:47:02
【问题描述】:
我有一个 react 组件,它包装了一个类,该类使用three.js 和 DOM 呈现 WebGL,并连接 mobx 存储值,它会随着类生命周期方法而变化。
传入的 mobx store 仅在生命周期函数中的组件渲染函数之外使用 (componentDidMount, componentDidUpdate, ..)。注意到当 store 改变时,组件不会触发重新渲染。但是我在渲染函数中进行了无用的读取,例如在下面的示例中,将 triggerRerenderListenerProp={this.props.store.debugSettings.showStats} 属性传递给 div,组件仅在 store.debugSettings.showStats 更改时才变为活动状态。
有没有办法让组件在渲染函数中不使用 store 来监听 store 的变化?
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {observer} from 'mobx-react';
import MapPreview from 'classes/MapPreview';
import style from './Preview.css';
class Preview extends Component {
static propTypes = {
store: PropTypes.object.isRequired,
imageUrl: PropTypes.string.isRequired
};
constructor (props) {
super(props);
this.containerEl = null;
}
componentDidMount () {
const options = {
debugSettings: this.props.store.debugSettings,
previewSettings: this.props.store.previewSettings
};
this.preview = new MapPreview(this.containerEl, options);
this.preview.setImage(imageUrl);
}
componentDidUpdate () {
this.preview.updateOptions({
debugSettings: this.props.store.debugSettings,
previewSettings: this.props.store.previewSettings
});
}
render () {
return (
<div
className={style.normal}
ref={(el) => { this.containerEl = el; }}
triggerRerenderListenerProp={this.props.store.debugSettings.showStats}
/>
);
}
}
export default observer(Preview);
【问题讨论】:
标签: javascript reactjs mobx mobx-react mobx-state-tree