window.postMessage 在 React 中没有 setTimeOut 的情况下无法在 componentDidMount 中工作

Red*_*ant 5 javascript node.js reactjs react-native

我正在研究在反应网页和反应本机网络视图之间传递数据。我想在网页加载后向移动设备上的 React-Native WebView 发送信号。

我想知道为什么在反应网页上,window.postMessage()除非与 一起使用,否则不起作用setTimeout。控制台中完全没有错误,但必须延迟大约 500 才能工作。谁能解释一下吗?我更喜欢回避,setTimeout因为感觉不可靠。

@observer
class TalkToMobile extends React.Component {
    @observable message;
    render() {
        return (
            <div>
                {
                    message ?
                        <Editor data={this.message}/>: null
                }
           </div>
        )
    }


    componentDidMount() {

        document.addEventListener('message', (e: any) => {
            if (e.data) {
                this.message = JSON.parse(e.data);
            }
        });

        let payload = {};
        payload.command = "giveMeData";
        window.postMessage(JSON.stringify(payload), "*")

        /*
        setTimeout(()=>{
            let payload = {};
            payload.command = "giveMeData";
            window.postMessage(JSON.stringify(payload), "*")
        }, 500);*/
    }
}
Run Code Online (Sandbox Code Playgroud)

dho*_*lik 3

您可能需要等待 Web 视图加载,然后再向其发送消息,因此从 Web 视图onLoad回调中执行此操作是有意义的。请尝试以下操作:

...
onWebViewLoaded() {
  if (this.webview) {
    this.webview.postMessage('');
  }
}

render() {
  return (
    <WebView
      ref={webview => { this.webview = webview }}
      source={{uri: 'https://facebook.github.io/react/'}}
      onLoad={this.onWebViewLoaded}
    />
  )
}
...
Run Code Online (Sandbox Code Playgroud)

如果您想将消息从 webview 发布到应用程序,请尝试在componentDidUpdate. 当它被触发时,DOM 已加载,并且不需要setTimeout