react-virtualized:在 AutoSizer 中设置状态

问题描述 投票:0回答:2

我正在使用 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
组件已完成构建)但我不知道如何解决它..

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

reactjs react-virtualized
2个回答
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>
  );
}


0
投票

我刚刚使用

<AutoSizer onResize={this.updateDimesions}>
来更新状态的维度,其中 updateDimeions 传递以下类型:

...
    updateDimesions = ({
        height,
        width
    }: {
        height: number;
        scaledHeight: number;
        scaledWidth: number;
        width: number;
    }) => {
        this.setState({ width, height });
    };
...
© www.soinside.com 2019 - 2024. All rights reserved.