【问题标题】:Using mobx store only outside of the react components render function仅在反应组件渲染功能之外使用 mobx 存储
【发布时间】: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


    【解决方案1】:

    这个问题最终有两个问题:

    • 第一,React 设计为仅在状态或道具数据更改时重新渲染。
    • 二,mobx-react,我很确定整点是除非您取消引用可观察值,否则组件不会重新渲染。

    因此,虽然您的 props 在技术上发生了变化,但 React 并没有对道具进行深入的对象比较。

    您可以尝试将options 设置为内部组件状态——可能强制重新渲染,即使渲染方法中的任何内容都不会改变。

    这里需要注意的是,更新后的props(来自您的商店)可能嵌套得太深,以至于即使在更新内部状态时也无法强制 React 重新渲染。您可能还需要搭载shouldComponentUpdate()

    【讨论】:

    • 我理解这个概念,更想知道解决方案是什么。现在创建了一个商店 onChange 侦听器,在更改时我会触发组件的更新。
    猜你喜欢
    • 2020-03-18
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多