React页面显示另一页的DOM错误。

huangapple go评论66阅读模式
英文:

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')
}

huangapple
  • 本文由 发表于 2023年7月11日 11:48:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定