【问题标题】:why Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.?为什么错误:重新渲染太多。 React 限制了渲染的数量以防止无限循环。?
【发布时间】:2022-01-14 00:58:42
【问题描述】:

错误:重新渲染过多。 React 限制渲染次数以防止无限循环 如何解决此问题以防止无限渲染?

不要将 ()=> 放在多个位置。

export default function Test1() {
  const [ref, inView] = useInView({ threshold: 0, triggerOnce: true });
  const [num, setNum] = useState(10);
  console.log(ref);

  if (inView) {
    setNum(num + 10);
    // console.log(num + 10);
  }

  return (
    <div>
      <Diiv1>123</Diiv1>
      <Diiv2 ref={ref}>Element {inView.toString()}</Diiv2>
      <Diiv3>789</Diiv3>
    </div>
  );
}
const Diiv1 = styled.div`
  width: 100%;
  height: 1500px;
  background-color: blue;
`;

const Diiv2 = styled.div`
  width: 100%;
  height: 1500px;
  background-color: red;
`;

const Diiv3 = styled.div`
  width: 100%;
  height: 1500px;
  background-color: blue;
`;


【问题讨论】:

    标签: reactjs use-effect use-state


    【解决方案1】:

    将其移至 useEffect

    useEffect(()=>{
      if (inView) {
        setNum(num + 10);
        // console.log(num + 10);
      }
    },[num,ref])
    
    
    

    更新: 实际上,您应该这样做:

      useEffect(() => {
        if (ref.threshold) {
          setNum(num + 10);
          // console.log(num + 10);
        }
      }, [ref,numb]);
    

    【讨论】:

    • 这行不通.. .. .. . ... . . .
    • 你能给我 useInView 钩子吗?
    猜你喜欢
    • 2021-06-24
    • 2021-01-22
    • 2021-07-01
    • 2021-05-17
    • 2021-02-04
    • 1970-01-01
    • 2020-08-06
    • 2021-10-21
    • 2020-09-22
    相关资源
    最近更新 更多