英文:
React Page showing DOM error of another page
问题
新手学习React。我想知道为什么我的React页面A会显示页面B的查询选择器错误。错误会无限循环,直到我跳转到页面B。
页面B中的代码:
function update(){
var checkExist = setInterval(function() {
if ($('#container').length) { //如果容器div存在
let container = document.querySelectorAll("#container")
let offbutton = container[0].querySelector('#offbutton')
}
clearInterval(checkExist);
}
}, 100);
}
代码更新:无法使用useEffect,因为它在另一个函数内部调用。
英文:
new to react. I was wondering why my React page A was showing query selector error of page B. The error loops like infinite times until I route to Page B.
Code in page B
Function update(){
var checkExist = setInterval(function() {
if (('#container').length) { //if container div exists
let container = document.querySelectorAll("#container")
let offbutton = container[0].querySelector('#offbutton')
}
clearInterval(checkExist);
}
}, 100);
}
Code Update : Cannot use useffect as this is called when inside another function
答案1
得分: 1
你可以使用 useEffect
钩子在组件挂载后和DOM准备就绪后运行你的查询选择器代码。
例如:
useEffect(() => {
var checkExist = setInterval(function () {
let container = document.querySelectorAll("#container");
if (container && container.length) {
let offbutton = container[0].querySelector("#offbutton");
}
}, 100);
return () => clearInterval(checkExist);
}, []);
英文:
You can use useEffect
hook to run your query selector code after the component is mounted and the DOM is ready.
For example:
useEffect(() => {
var checkExist = setInterval(function () {
let container = document.querySelectorAll("#container");
if (container && container.length) {
let offbutton = container[0].querySelector("#offbutton");
}
}, 100);
return () => clearInterval(checkExist);
}, []);
答案2
得分: 1
问题出在这一行
if (('#container').length) {
它总是返回true。因为字符串"#container"的长度是10,而且是真值。
请尝试这个
let container = document.querySelectorAll("#container")
if (container && container.length) {
let offbutton = container[0].querySelector('#offbutton')
}
英文:
The problem is with this line
if (('#container').length) {
It would return true always. Because the length of the string "#container" is 10, and is truthy.
Please try this
let container = document.querySelectorAll("#container")
if (container && container.length) {
let offbutton = container[0].querySelector('#offbutton')
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论