javascript - react : How to read from the DOM after mount?

标签 javascript dom reactjs flux

在我的 React 组件中,我需要在 DOM 可供我的应用程序的后续部分使用时从中读取数据。我需要将数据保存到状态中,并通过分派(dispatch)操作通过 Flux 发送它。是否有这样做的最佳实践?

更具体地说,在至少两种情况下我需要来自 DOM 的数据:

  • 视觉上直接,因为用户看到的第一件事应该是“正确的”,这涉及基于从 DOM 读取的数据的计算。
  • 稍后使用的数据(例如用户移动鼠标),但基于初始 DOM 状态。

请考虑以下事项:

  • 我需要从 DOM 中读取并保存数据。此 DOM 在 componentDidMount 中可用,但是我无法在 componentDidMount 中调度操作,因为这将导致在调度期间调度 错误。由于这个原因,在 component*mount 中调度是 React 中的反模式。
  • 通常的解决方法(hack)是将调度放在 setTimeout( ..., 0 ) 调用中的 componentDidMount 中。 我想避免这种情况,因为它看起来纯粹是一种绕过 Flux 错误的黑客攻击。如果真的没有更好的答案,我会接受,但很不情愿。
  • 不要用不要从 DOM 中读取来回答这个问题。这与我的问题无关。我知道这会将我的应用程序耦合到 DOM,而且我知道这不是我们想要的。同样,我问的问题与我是否应该使用此方法无关。

最佳答案

这是我在反流中使用的模式。

export default class AppCtrl extends AppCtrlRender {
  constructor() {
    super();
    this.state = getAllState();
  }

  componentDidMount = () => {
    // console.log('AppCtrl componentDidMount');
    this.unsubscribeApp = AppStore.listen(this.appStoreDidChange);
    this.unsubscribeGS = GenusSpeciesStore.listen(this.gsStoreDidChange);
    Actions.setWindowDefaults(window);
  }
  componentWillUnmount = () => { this.unsubscribeApp(); this.unsubscribeGS(); }
  appStoreDidChange = () => { this.setState(getAppState()); }
  gsStoreDidChange = () => { this.setState(getGsState()); }
  shouldComponentUpdate = (nextProps, nextState) => {
    return nextState.appStoreChanged && nextState.gsStoreChanged;
  }
}

在 app.store.js 中

function _windowDefaults(window) {
  setHoverValues();
  let deviceTyped = 'mobile';
  let navPlatform = window.navigator.platform;
  switch (navPlatform) {
    case 'MacIntel':
    case 'Linux x86_64':
    case 'Win32': deviceTyped = 'desktop'; break;
  }
  //deviceTyped = 'mobile';
  _appState.deviceType = deviceTyped;
  _appState.smallMobile = (deviceTyped == 'mobile' && window.screen.width < 541);
  //_appState.smallMobile = (deviceTyped == 'mobile');
  if (deviceTyped == 'desktop') {
    let theHeight = Math.floor(((window.innerHeight - 95) * .67));
    // console.log('_windowDefaults theHeight: ', theHeight);
    _appState.commentMaxWidth = theHeight;
    _appState.is4k = (window.screen.width > 2560);
    Actions.apiGetPicList();
  } else {
    React.initializeTouchEvents(true);
    _bodyStyle = {
      color: "white",
      height: '100%',
      margin: '0',
      overflow: 'hidden'
    };
    AppStore.trigger();
  }
}

关于javascript - react : How to read from the DOM after mount?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33864038/

相关文章:

javascript - "Process is not defined"与react-chartjs-2 CDN

javascript - 如何将部分 Redux 存储转换为数组

javascript - 两个foreach替换JS

javascript - 立即/自执行函数语法 : Parentheses vs Negation Operator (and other Operators)?

javascript - getBoundingClientRect 根据滚动位置动态变化?

javascript - 如何分别检索父元素内子元素之前和之后的 HTML?

javascript 在我的客户端和服务器文件夹之间共享代码

javascript - slick 在 slider 的末尾有空幻灯片

即使在文档末尾调用函数,Javascript getElementById 也找不到 div

php - 如果可以选择,使用 JQuery 还是 PHP 构建 DOM 元素更好?