在我的 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/