问题

我正在尝试从startIndex内部将onRowsRendered()置于状态。

在将CellMeasurer放入混合之前,此方法都可以正常工作。

向下滚动然后向上滚动时,会出现以下错误:


  未捕获的恒定违反:超出最大更新深度。当组件在setStatecomponentWillUpdate中重复调用componentDidUpdate时,可能会发生这种情况。 React限制了嵌套更新的数量,以防止无限循环。


是什么导致了这个问题,又是什么解决了呢?

演示版


with CellMeasurer(错误)
without CellMeasurer(无错误)






import React from "react";
import ReactDOM from "react-dom";
import faker from "faker";
import { List, CellMeasurer, CellMeasurerCache } from "react-virtualized";

import "./styles.css";

faker.seed(1234);

const rows = [...Array(1000)].map(() =>
  faker.lorem.sentence(faker.random.number({ min: 5, max: 10 }))
);

const App = () => {
  const [currentIndex, setCurrentIndex] = React.useState(0);

  const rowRenderer = ({ key, index, style, parent }) => {
    return (
      <div style={style}>
        <div style={{ borderBottom: "1px solid #eee", padding: ".5em 0" }}>
          {rows[index]}
        </div>
      </div>
    );
  };

  return (
    <>
      <h1>{currentIndex}</h1>
      <p>
        <em>When scrolling down and then up, an error occurs. Why?</em>
      </p>
      <List
        height={400}
        width={600}
        rowCount={rows.length}
        rowHeight={35}
        rowRenderer={rowRenderer}
        style={{ outline: "none" }}
        onRowsRendered={({ startIndex }) => {
          setCurrentIndex(startIndex);
        }}
      />
    </>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

最佳答案

您需要将rowRenderercellMeasurer函数移到功能组件之外。因为它将在每次渲染功能组件时重新创建。

功能组件:
https://codesandbox.io/s/nnp9z3o9wj?fontsize=14

或者您可以使用类组件:

import React from "react";
import ReactDOM from "react-dom";
import faker from "faker";
import { List, CellMeasurer, CellMeasurerCache } from "react-virtualized";

import "./styles.css";

faker.seed(1234);

const rows = [...Array(1000)].map(() =>
  faker.lorem.sentence(faker.random.number({ min: 5, max: 10 }))
);

class VirtualList extends React.Component {


 rowRenderer = ({ key, index, style, parent }) => {
    return (
      <div style={style}>
        <div style={{ borderBottom: "1px solid #eee", padding: ".5em 0" }}>
          {rows[index]}
        </div>
      </div>
    );
  };

  render() {
     return (
      <List
        height={400}
        width={600}
        rowCount={rows.length}
        rowHeight={35}
        rowRenderer={this.rowRenderer}
        style={{ outline: "none" }}
        onRowsRendered={this.props.setCurrentIndex}
      />
     )
   }
}

const App = () => {
  const [currentIndex, setCurrentIndex] = React.useState(0);


  return (
    <>
      <h1>{currentIndex}</h1>
      <p>
        <em>When scrolling down and then up, an error occurs. Why?</em>
      </p>
      <VirtualList setCurrentIndex={setCurrentIndex} />
    </>
  );
};

09-16 09:02