【问题标题】:react-virtualized: SetState in AutoSizer反应虚拟化:AutoSizer 中的 SetState
【发布时间】:2021-09-03 05:35:19
【问题描述】:

我正在使用 React-Virtualized。
我想设置 AutoSizer 宽度的状态,但它给了我警告。

Warning: Cannot update a component (`App`) while rendering a different component (`AutoSizer`). To locate the bad setState() call inside `AutoSizer`, follow the stack trace as described in ....

我明白为什么它会给我这个警告(我在整个之前调用 setState
组件已完成构建)但我不知道如何解决它..

这是一个代码框示例:
https://codesandbox.io/s/gracious-maxwell-53y2i?file=/src/App.js

【问题讨论】:

    标签: reactjs react-virtualized


    【解决方案1】:

    我找到了一个丑陋的解决方案:

    import "./styles.css";
    import { AutoSizer } from "react-virtualized";
    import React, { useEffect, useState, useRef, useCallback } from "react";
    
    export default function App() {
      const [tableWidth, setTableWidth] = useState(0);
    
      const refCallback = useCallback((ref, width) => {
        if (ref) {
          setTableWidth(width);
        }
      }, []);
    
      return (
        <div className="App">
          <p>AutoSizer: width = {tableWidth}</p>
          <AutoSizer>
            {({ height, width }) => {
              return <p ref={(ref) => refCallback(ref, width)}>Here another component</p>;
            }}
          </AutoSizer>
        </div>
      );
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-28
      • 2018-01-23
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 2017-12-03
      • 2017-07-13
      相关资源
      最近更新 更多