【问题标题】:Need guidance on encapsulating logic in a react-based data table需要有关在基于反应的数据表中封装逻辑的指导
【发布时间】:2018-05-02 21:16:58
【问题描述】:

我正在尝试使用 react-virtualized 创建一个可重用的反应数据表组件,并且需要有关状态管理的指导。

我已经实现了服务器端过滤/排序/无限滚动,并且正在使用本地组件状态来存储表上下文(过滤器、当前页面、数据行等)。

简化示例:

  class DataTableWithFilter
      render() {
        return ( 
              <React.Fragment>
              <DataTableFilterBar
                   value={this.state.filter}
                   onFilterChange={this._handleFilterChange}
                   onSort={this._handleSort}
                   onScroll={this._handleScroll}
               />
              <VirtualizedDataTable
                  records={this.state.records}
              />                      
              </React.Fragment>
        )
      }
      _handleFilterChange() {
         // build up url from state (path, filter, sort index, page index, etc)
         // fetch new data
         // put new data into state
      }
      _handleSort() {...}
      _handleScroll() {...}
      etc
  }

不惜一切代价,我试图避免复制表格中使用的任何逻辑并将其完全封装在表格组件中。该表格将被使用数十次,因此我希望表知道如何加载自己的数据并处理排序/过滤/滚动,并在不同的上下文中使用。

但这变得越来越复杂,因为表的不同用途需要父组件和兄弟组件能够告诉表重新加载它的数据。 示例包括一个“添加新记录”按钮,该按钮弹出一个模式,然后在将新记录发布到服务器后需要重新加载表。或“删除记录”按钮,需要在将删除内容发布到服务器后重新加载数据表。

我看到了几个选项:

1) 制作一个整体 EditableDataTableWithFilter 组件,其中包含所有状态和过滤/排序/滚动/模态/按钮行为,并可选择呈现某些子组件,如过滤栏或模态。缺点是将所有东西都放在一个组件中,并且在将组件用作简单数据表而没有过滤或上下文相关的按钮/模式时,会有很多不必要的行为。这看起来很糟糕。

2) 创建一个 EditableDataTable 组件,该组件呈现一个子 DataTableWithFilter 组件,并添加显示和提交模态数据所需的逻辑。我假设这样做将再次要求将表数据向上移动到 EditableDataTable 本地状态并作为道具传递给 DataTableWithFilter,以便在数据更改时重新加载表。或者,我需要找到某种方法来“告诉”子 DataTableWithFilter 重新加载其数据。后者,使用 refs 或类似的方法似乎是一种再次破坏封装的糟糕方法。而且我也不确定如何将属性用作“重新加载触发器”。

3) 使用像 redux 这样的集中式状态提供程序。我还没有在项目中引入redux,但我想知道这是否是最好的解决方案。

【问题讨论】:

  • 请通过:stackoverflow.com/questions/49107940/… .... 当我想避免 redux 时,我会这样做。
  • 对。但是您将如何处理这种情况: 并且希望 与或不与可能影响它的模态(或其他组件)一起使用.

标签: reactjs datatable datagrid redux react-redux


【解决方案1】:

在组件结构下面找到(它只是一个伪代码)。 ok_cb、cancel_cb 是传递给 ModalThatNeedsToReloadTable 组件的回调,并从 ModalThatNeedsToReloadTable 组件中调用。回调将使用 setState() 方法在状态中设置所需的数据,这将重新渲染整个容器组件。希望这会有所帮助。

<Container>
    // in this component you can set the data shared between all
    // the components within the container in the components 'state'

    cancel_cb() {
        // this cb will call the set state
        // method which will re-render the component
    }

    ok_cb() {
        // this cb will call the set state
        // method which will re-render the component
    }


    render()

        if(this.props.showModal)
            <ModalThatNeedsToReloadTable show={this.state.showModal}
                onCancelClick={this.cancel_cb}
                onOKClick={this.ok_cb}/>

        <SmartTableComponent> <DumbTableComponent> </SmartTableComponent>

</Container>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2016-07-17
    • 2010-12-22
    • 2016-08-16
    相关资源
    最近更新 更多