将react-virtualized List的当前索引设置为state时发生错误

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

问题

我试图把startIndex放在onRowsRendered()内。

这很好,直到CellMeasurer进入组合。

向下滚动然后向上滚动时,会发生以下错误:

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

是什么导致了这个问题以及解决了什么问题?

演示

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);
javascript reactjs setstate react-virtualized
1个回答
1
投票

您需要在功能组件之外移动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} />
    </>
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.