如何解决如何避免Reactjs错误:重新渲染太多React限制了渲染次数以防止无限循环从组件下方
export function UsePageVisibility() {
const [isVisible,setIsVisible] = React.useState(getIsDocumentHidden());
console.log(isVisible);
const onVisibilityChange = () => setIsVisible(getIsDocumentHidden());
React.useEffect(() => {
const visibilityChange = getbrowserVisibilityProp();
window.addEventListener(visibilityChange,onVisibilityChange,false);
return () => {
window.removeEventListener(visibilityChange,onVisibilityChange);
};
},[]);
return isVisible;
}
Test.js :
import React,{ useState } from "react";
import "./App.css";
import Component from "./component";
export function getbrowserVisibilityProp() {
if (typeof document.hidden !== "undefined") {
// Opera 12.10 and Firefox 18 and later support
return "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
return "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
return "webkitvisibilitychange";
}
}
export function getbrowserDocumentHiddenProp() {
if (typeof document.hidden !== "undefined") {
return "hidden";
} else if (typeof document.msHidden !== "undefined") {
return "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
return "webkitHidden";
}
}
export function getIsDocumentHidden() {
return !document[getbrowserDocumentHiddenProp()];
}
export function UsePageVisibility() {
const [isVisible,setIsVisible] = React.useState(getIsDocumentHidden());
const [counter,setcounter] = useState(false);
console.log(isVisible);
const onVisibilityChange = () => setIsVisible(getIsDocumentHidden());
React.useEffect(() => {
const visibilityChange = getbrowserVisibilityProp();
window.addEventListener(visibilityChange,[]);
if (!isVisible) {
setcounter(true);
} else {
setcounter(false);
}
return isVisible;
}
App.js :
import React from "react";
import "./App.css";
import { UsePageVisibility } from "./test";
class App extends React.Component {
render() {
return <UsePageVisibility />;
}
}
export default App;
解决方法
一旦安装了组件,就会有一个函数自行调用。
尝试:
const onVisibilityChange = () => setIsVisible(() => getIsDocumentHidden());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。