如何在Chrome API中使用react setState [英] How to use react setState with chrome API
问题描述
我想在Chrome API中使用react的 setState
,但是我遇到了问题...
I want to use react's setState
with chrome API but I'm running into an issue...
componentDidMount() {
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
this.setState({sourceCode: request.source});
}
});
}
我尝试了以下操作,但是chrome API无法将 setState
识别为函数,因此我尝试首先将 request.source
保存为变量... >
I tried the following but chrome API does not recognize setState
as a function, so then I tried to first save request.source
as a variable...
componentDidMount() {
var source = "";
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
source = request.source;
}
});
this.setState({sourceCode: source});
}
但是当我尝试以下操作时, source
仍然是一个空字符串.我不知道为什么,因为 source
被设置为 request.source
.我该如何解决?
But when I try the following, source
remains an empty string. I cannot figure out why since source
is being set to request.source
. How can I fix this?
编辑
我这样称呼脚本...
I am calling a script as so...
chrome.tabs.executeScript(null, {
file: 'src/js/scripts/getPageSource.js'
}, function() {
...
在脚本中,我有以下内容...
and inside the script I have the following...
chrome.runtime.sendMessage({
action: "getSource",
source: DOMtoString(document)
});
DOMtoString
函数仅返回一个字符串.它是由我的 componentDidMount
捕获的,已通过在if语句内打印到控制台进行验证.
Where DOMtoString
function simply returns a string. It is the caught by my componentDidMount
which I have verified by printing to the console inside the if statement.
引起我注意的是 addListener
是异步的.有什么方法可以将结果保存到状态中?
It has come to my attention that the addListener
is asynchronous. Is there any way I can save the result in the state?
推荐答案
您需要绑定 this
,以便在事件侦听器中保持不变
You need to bind this
so it is unchanged in the event listener
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
this.setState({sourceCode: request.source});
}
}.bind(this));
您的第二次尝试不起作用,因为回调是异步的.回调返回时,您需要调用 setState
.在第二次尝试中,您注册了侦听器,然后立即调用setState.
Your second attempt doesn't work because the callback is asynchronous. You need to call setState
when the callback returns. In your second attempt, you register for the listener but then immediately call setState.
或者,您可以改用箭头功能.这将用词法绑定 this
,因此它将保持不变.
Alternatively, you could switch to using arrow functions instead. This would lexically bind this
so it would be unchanged.
chrome.runtime.onMessage.addListener((request, sender) => {
if (request.action == "getSource") {
this.setState({sourceCode: request.source});
}
});
这篇关于如何在Chrome API中使用react setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!