【发布时间】:2019-11-02 12:06:16
【问题描述】:
我有一个函数handleScroll 监听滚动事件。该函数必须更新 isFetching(以 false 开头并且必须更改布尔值)。
handleScroll 函数被正确监听,如console.log 所示。但是,isFetching 始终为假。
似乎从未阅读过setIsFetching。我认为另一种选择就像 eventListener 冻结了 handleScroll 函数的第一个版本。
如何才能更新该函数中的挂钩? 这是代码的简化版本和codesandbox:
/* <div id='root'></div> */
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const debounce = (func, wait, immediate) => {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args);
};
};
const App = () => {
const [isFetching, setIsFetching] = useState(false);
const handleScroll = debounce(() => {
setIsFetching(!isFetching);
console.log({ isFetching });
}, 300);
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return <div style={{ height: "1280px" }}>Hello world</div>;
};
const root = document.getElementById("root");
if (root) ReactDOM.render(<App />, root);
更新
我将一个空数组作为第二个参数放在 useEffect 中,因为我希望第一个参数函数只在 componentDidMount() 上触发一次
【问题讨论】:
标签: javascript reactjs events react-hooks