[英]React: How to read from the DOM after mount?
在我的React组件中,当需要为我的应用程序的后续部分工作时,我需要从DOM中读取数据。 我需要将数据保持在状态,并通过调度动作通过Flux发送。 这样做有最好的做法吗?
更具体地说,我至少需要两种情况下来自DOM的数据:
请考虑以下事项:
componentDidMount
中可用, 但是我无法在componentDidMount
调度操作,因为这会在调度错误期间发送调度 。 因此,在component*mount
调度是React中的反模式。 componentDidMount
中的setTimeout( ..., 0 )
调用中。 我想避免这种情况,因为它看起来纯粹像是一个绕过Flux错误的黑客。 如果真的没有更好的答案,我会接受它,但不情愿。 这是我在回流中使用的模式。
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(); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.