我正在尝试使2个React应用程序版本相互通信(第16到15个反应)。我想以单向方式将消息从我的react16应用传递到我的react15。我发现将旧应用程序升级到新版本并不可行,因为在开发新版本的同时,我只需要一些工作即可。
所以我的react 16应用程序基本上要做的是它已经向chrome扩展程序发送了一条消息,而该扩展程序将依次返回dataUrl。然后,将dataUrl渲染到画布上,然后在编辑图像后使用axios将其发送到Firebase进行存储。然后,Firebase将收到一个响应,我希望使用事件侦听器将其发送到react 15应用。
我尝试过的是,当图像成功发送到数据库时,react 16应用将执行window.postMessage()。较早的应用程序在componentDidMount()上具有事件监听器,应该可以捕获消息。
当我进行此运行时,它将无法正常运行。 postMessage没问题,但似乎eventListener没有捕获它。
任何帮助将不胜感激。谢谢!
React 16应用 ImageContainer.js
...
axios.post('/screenshots.json', submittedImage)
.then(response => {
this.setState({ showPrompt: false })
response.status === 200 ? this.props.notify(true, "Screenshot Saved! ") : this.props.notify(false)
this.props.storeImageToArrayHandler(submittedImage)
let firebaseId = response.data.name // This will be used for single querying the image from firebase
let feedBackButton = document.getElementById('feedback-button');
feedBackButton.click();
var data = { type: "FROM_REACT16", text: "Enter Image ID" };
console.log("[ImageContainer] Sending Message...")
window.postMessage(data, "*");
this.setState({ showImageContainer: false })
})
.catch(error => {
this.setState({ showPrompt: false })
this.props.notify(false, "Unable to save Screenshot. " + error)
this.props.storeImageToArrayHandler("")
})
...
React 15应用 MainContainer.js
...
componentDidMount() {
console.log("[componentDidMount] MainContainer.js")
window.addEventListener("image_interceptor", function (event) { //listen for messages from react app
console.log("[MainContainer] Listening for messages...")
if (event.data.type && (event.data.type === "FROM_REACT16")) {
console.log('I got the message');
}
return true;
});
window.mainContainer = {
addStateValidator: this.addStateValidator,
};
this.props.start();
}
...
index.html
...
<BODY>
<div style=" width: 100%; height:100%; position: absolute;; top:0; left:0; bottom:0; right:0;">
<div id="notification" style="display:inline;">
<p>Extension not detected.
You can download the extension <a
href="www.link-to-extension.com">here</a>
.
</p>
</div>
</div>
<div id="root"></div> //REACT 15
<div id="screenshot"></div> //REACT 16
<script src="feedback/feedback-main.js" type="text/javascript" charset="utf-8"></script>
<script src="feedback/bundle.js" type="text/javascript" charset="utf-8"></script>
</BODY>
</HTML>