【问题标题】:Why is the console coming out differently in useEffect?为什么控制台在 useEffect 中出现不同?
【发布时间】:2022-02-09 17:27:06
【问题描述】:

我想确保滚动条位于区域的中间以防滚动。


const scrollRef = useScroll(null);

useEffect(() => {
    const wrapper = scrollRef.current;
    console.dir(wrapper, 'wrapper');
    if (wrapper) {
      const hasScroll = wrapper.scrollHeight > wrapper.clientHeight;
      console.log(wrapper.scrollHeight, 'scrollheight');
      console.log(wrapper.clientHeight, 'clientHeight');
      if (hasScroll) {
        const scrollTop = (wrapper.scrollHeight - wrapper.clientHeight) / 2;
        wrapper.scrollTop = scrollTop;
      }
    }
  }, [isLoading]);

if (isLoading) {
    return (
      <TradeSection>
        <Loader />
      </TradeSection>
    );
  }

<Section>
  <TableHeader>
  <TableList ref={scrollRef}>
    <List />
    <CurrentPrice />
    <List />
  </TableList>
<Section>

此代码总体上运行良好。 但有时它不起作用 根据我的猜测,如果你在屏幕尺寸改变后刷新, 所以我在 useEffect 中添加了控制台

为什么 console.dir > scrollHeight 是不同的结果? 为什么在同一区域显示不同的值?

【问题讨论】:

    标签: reactjs scrollview scrollbar use-effect console.log


    【解决方案1】:

    当当前 ref 值更改时,您的 useEffect 不会更新。这意味着您的控制台日志会在 isLoading 更新时触发,但不会捕获 scrollRef.current 的最终值。

    只有在useEffect 可以实际跟踪该值的更改时,将某些内容放入useEffect 才有帮助。不幸的是,useRef 无法做到这一点,因为对象 ref 不会通知您的组件有关当前 ref 值的更改。对于这个用例,正确的钩子实际上是useCallback;请参阅此React FAQ answer 以获得解释和一些类似的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多