Javascript window.postMessage在componentDidMount中不工作,而在React中未设置超时
我正致力于在react网页和react原生网络视图之间传递数据。我想在网页加载后向手机上的react native webview发送一个信号 我想知道为什么在react网页上,除非与Javascript window.postMessage在componentDidMount中不工作,而在React中未设置超时,javascript,node.js,reactjs,react-native,Javascript,Node.js,Reactjs,React Native,我正致力于在react网页和react原生网络视图之间传递数据。我想在网页加载后向手机上的react native webview发送一个信号 我想知道为什么在react网页上,除非与setTimeout一起使用,否则window.postMessage()不起作用。控制台中根本没有错误,但它必须延迟大约500才能工作。有人能解释一下吗?我更喜欢避免设置超时,因为它感觉不可靠 @observer class TalkToMobile extends React.Component { @
setTimeout
一起使用,否则window.postMessage()
不起作用。控制台中根本没有错误,但它必须延迟大约500才能工作。有人能解释一下吗?我更喜欢避免设置超时,因为它感觉不可靠
@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);*/
}
}
@observer
类TalkToMobile.Component{
@可观察信息;
render(){
返回(
{
消息
:null
}
)
}
componentDidMount(){
document.addEventListener('消息',(e:any)=>{
如果(如数据){
this.message=JSON.parse(e.data);
}
});
让有效载荷={};
payload.command=“giveMeData”;
window.postMessage(JSON.stringify(有效负载),“*”)
/*
设置超时(()=>{
让有效载荷={};
payload.command=“giveMeData”;
window.postMessage(JSON.stringify(有效负载),“*”)
}, 500);*/
}
}
您可能需要等待webview加载后再向其发布消息,因此从webviewonLoad
回调中执行此操作是有意义的。请尝试以下操作:
。。。
onWebViewLoaded(){
if(this.webview){
this.webview.postMessage(“”);
}
}
render(){
返回(
{this.webview=webview}
source={{uri:'https://facebook.github.io/react/'}}
onLoad={this.onWebViewLoaded}
/>
)
}
…