【问题标题】:react-virtualized dynamically updating Gridreact-virtualized 动态更新 Grid
【发布时间】:2017-08-10 01:28:29
【问题描述】:

我将react-virtualized Grid中的简单示例修改如下。虽然这段代码有效,但我有一个两部分的问题:

  1. 如何修改示例,以便在 timer callbackquoteChange 上 使用随机值调用。
  2. 如果我修改quoteListGrid会自动更新而不调用cellRenderer吗?

代码。我们的想法是让应用程序看起来像是在显示流式实时报价。请注意,quoteChange 目前没有做任何事情。这是我第一次尝试的微弱尝试。

import React from 'react';
import ReactDOM from 'react-dom';
import { Grid } from 'react-virtualized';

// Grid data as an array of arrays
const quoteList = [
  ['GE', 100, 35.28, 35.30, 100, 95125],
  ['IBM', 100, 135.11, 135.20, 100, 195125],
  ['C', 100, 45.23, 45.30, 100, 195125]
];

function quoteChange(ri, bid, ask)
{
    quoteList[ri][2] = bid
    quoteList[ri][3] = ask

    var bi = {
        columnIndex : 2,
        rowIndex : ri,
    }

    cellRenderer(bi)

    var ba = {
        columnIndex : 3,
        rowIndex : ri,
    }

    cellRenderer(ba)
}

function cellRenderer ({ columnIndex, key, rowIndex, style }) {
  return (
    <div
      key={key}
      style={style}
    >
      {quoteList[rowIndex][columnIndex]}
    </div>
  )  
}

// Render your grid
ReactDOM.render(
  <Grid
    cellRenderer={cellRenderer}
    columnCount={quoteList[0].length}
    columnWidth={50}
    height={quoteList.length * 20}
    rowCount={quoteList.length}
    rowHeight={20}
    width={800}
  />,
  document.getElementById('root')
);

【问题讨论】:

    标签: javascript reactjs timer callback react-virtualized


    【解决方案1】:

    如果我修改了quoteList,Grid会自动更新而不调用cellRenderer吗?

    没有。这是提到at the beginning of the docs。 ;)

    纯组件

    默认情况下,所有 react-virtualized 组件都使用 shallowCompare 来避免重新渲染,除非 props 或 state 发生了变化。当集合的数据发生变化(例如 ['a','b','c'] => ['d','e','f'])但 props 没有变化(例如 array.length)时,这有时会让用户感到困惑。

    解决这个问题的方法是让 react-virtualized 知道外部的东西发生了变化。这可以通过几种不同的方式完成。

    直通道具

    shallowCompare 方法将检测任何 props 的更改,即使它们未声明为 propTypes。这意味着您还可以传递影响单元格渲染的其他属性,以确保检测到更改。例如,如果您使用List 来呈现可能在初始呈现后重新排序的项目列表,react-virtualized 通常不会检测到排序操作,因为它处理的属性没有任何变化。但是,您可以通过附加的排序属性来触发重新渲染。例如:

    <List
      {...listProps}
      sortBy={sortBy}
    />
    

    公共方法

    GridCollection 组件可以使用 forceUpdate 强制重新渲染。对于TableList,您需要调用forceUpdateGrid 以确保内部Grid 也被更新。

    【讨论】:

    • 谢谢。因此,在 Grid 示例中,我应该将什么传递给 Grid 以使其在 quoteList 项目更改时重绘(不是对整个列表列表的操作,只是 lsingle 列表项目更改)?我假设 forceUpdate 很昂贵,因为它可能会重绘整个网格。
    • 我的解决方案:我已经使用传递给网格的相同数据定义了组件的状态,而不是像示例告诉的那样将{...listProps} 定义到 che Grid 组件中。然后,使用componentWillReceiveProps() 我将使用新数据更新状态。这会导致在数据更改时重新渲染组件。希望这会有所帮助。
    • 在表格示例中,我应该在哪里调用forceUpdateGrid()?在我的自定义反应组件的render() 函数中,它包装了&lt;Table /&gt;?谢谢!
    • UNSAFE_componentWillReceiveProps() 现在被标记为“不安全”。我们应该改用什么?
    • @YixingLiu 这篇博文详细介绍了这一点:reactjs.org/blog/2018/03/27/update-on-async-rendering.html
    猜你喜欢
    • 2019-09-21
    • 2018-04-01
    • 2020-09-17
    • 2017-07-04
    • 2017-06-29
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多