React Hooks useState显示错误

时间:2020-04-08 07:40:59

标签: javascript reactjs react-hooks use-effect

import React, { useState, useEffect } from 'react';
import ReactScrollDetector from 'react-scroll-detector';

const DatePicker = ({ count }) => {
  const [countNew, setCount] = useState(count);
  const handleScrollBottom = () => {
    useEffect(() => setCount((countNew = countNew + 12)));
  };

  const handleScrollTop = () => {
    useEffect(() => setCount((countNew = countNew + 12)));
  };

  return (
    <ReactScrollDetector
      debounceTime={500}
      accuracy={90}
      onScrollBottom={handleScrollBottom}
      onScrollTop={handleScrollTop}
    >
      <div style={{ minHeight: '300px', maxHeight: '300px', overflow: 'auto' }}> </div>
    </ReactScrollDetector>
  );
};

react-dom.development.js:55未捕获的不变违规:无效的钩子 呼叫。挂钩只能在函数体内调用 零件。发生这种情况可能是由于以下原因之一:

  1. 您可能使用了不匹配的React和渲染器版本(例如React DOM)
  2. 您可能正在违反挂钩规则
  3. 您可能在同一应用中拥有多个React副本

2 个答案:

答案 0 :(得分:2)

尝试一下:

    import React, { useState, useEffect } from "react";
    import ReactScrollDetector from "react-scroll-detector";

    const DatePicker = ({count}) => {
      const [countNew, setCount] = useState(count)
      const handleScrollBottom = () => {
          setCount(countNew + 12)
       }
      const handleScrollTop = ()  => {
        setCount(countNew + 12)
     }
      return (
        <ReactScrollDetector
          debounceTime={500}
          accuracy={90}
          onScrollBottom={handleScrollBottom}
          onScrollTop={handleScrollTop}>
          <div style={{ minHeight: "300px", maxHeight: "300px", overflow: "auto" }}> <div>

        </ReactScrollDetector>
      );
    };

答案 1 :(得分:1)

让您这样的功能

const handleScrollBottom = () => setCount(countNew = countNew + 12))
       
const handleScrollTop = ()  => setCount(countNew = countNew + 12)) 

错误

react-dom.development.js:55 Uncaught Invariant Violation:

是因为useEffect Hook需要位于函数之外

export default function MyComponent() {
  useEffect(() => {
      
  }, []);
  const bar = () => {};
  const foo = () => {};
  return <div></div>;
}