反应虚拟化:AutoSizer 中的 SetState

问题描述

我正在使用 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

解决方法

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

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>
  );
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...