在滚动React钩子上更新状态

时间:2020-11-02 05:31:59

标签: javascript reactjs

我希望能够随着用户滚动来更新我的状态。

这是我所拥有的近似值:

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [scrollNumber, updateScrollNumber] = useState(0);
  const onScroll = () => updateScrollNumber(scrollNumber + 12);

  useEffect(() => {
    document.addEventListener('scroll', (event) => onScroll())
  },[])
  return (
    <div onScroll={onScroll} className="App" style={{ height: 200000 }}>
      {console.log({ scrollNumber })}
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

为什么scrollNumber不更新?

这里是sandbox

3 个答案:

答案 0 :(得分:1)

第一个问题是您要将onScroll事件添加到div中。如果在div中滚动,它将被调用。但实际上,您正在窗口中滚动。因此,您需要在窗口滚动上附加一个事件侦听器。为此,您可以像这样使用useEffect钩子。

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [scrollNumber, updateScrollNumber] = useState(0);
  
  useEffect(() => {
      window.addEventListener("scroll", onScroll);
      return () => window.removeEventListener("scroll", onScroll);
  }, [scrollNumber]);

  const onScroll = () => {
    console.log("updating the scrollNumber");
    updateScrollNumber(scrollNumber + 12);
  };
  return (
    <div className="App" style={{ height: 200000 }}>
      {console.log({ scrollNumber })}
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

要详细了解滚动事件,请查看here

答案 1 :(得分:0)

2020-11-01 21:53:21,775 INFO sqlalchemy.engine.base.Engine UPDATE blobs SET data=? WHERE blobs.hash = ?
2020-11-01 21:53:21,775 INFO sqlalchemy.engine.base.Engine (<memory at 0x10931b640>, 'qz78diGV8TjV31akJUBfHZUopUX5iC7rnHIUhQ==')
2020-11-01 21:53:21,775 INFO sqlalchemy.engine.base.Engine COMMIT

答案 2 :(得分:0)

问题是您在div中使用过onSroll。如果您希望能够在div内完成此操作;将其属性溢出设置为滚动。如果您希望它在窗口滚动中起作用;添加一个eventListener。

这应该有效:

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [scrollNumber, updateScrollNumber] = useState(0);
  const onScroll = () => updateScrollNumber(scrollNumber + 12);
  useEffect(() => {
    window.addEventListener("scroll", onScroll)
    return () => window.removeEventListener("scroll", onScroll)
  })

  return (
    <div
      onScroll={onScroll}
      className="App"
      style={{ height: 200000}}
    >
      {console.log({ scrollNumber })}
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}