使用React创建可重复使用的过滤表时出现问题

时间:2018-12-21 17:13:14

标签: javascript reactjs

我正在尝试创建一个可重用的表组件,在该组件中,我只能作为道具数据过滤器的传递对象,它已经为我完成了大部分工作。但是,现在,我正在将选择变量硬编码为Table状态,如果要使用不同的过滤器创建另一个表,则必须为此创建另一个组件。无论如何,这是不可行的。

现在我有一个主组件,用于保存数据和过滤器,并向下传递到Table组件,像这样:

class Master extends React.Component {
   listHotels: [
      createObject('BlueTree','05-02-2015','ativo', 'Vinhedo', 'São Paulo'),
      createObject('Inner','07-08-2016','inativo', 'Belo Horizonte', 'Minas Gerais'),
      createObject('Teste','05-02-2017','ativo', 'Teresina', 'Piauí'),
      createObject('hello','05-02-2015','ativo', 'Osasco', 'São Paulo'),
      createObject('Inner','07-08-2016','inativo', 'Lavras', 'Minas Gerais'),
      createObject('Teste','05-02-2017','inativo', 'Barras', 'Piauí'),
      createObject('xiaomi','05-02-2015','inativo', 'Indaiatuba', 'São Paulo'),
      createObject('Inner','07-08-2016','ativo', 'Pedrinhas', 'Minas Gerais'),
      createObject('Teste','05-02-2017','ativo', 'Esperantina', 'Piauí'),
    ].sort((a, b) => (a.id < b.id ? -1 : 1)),
    selectFilter: [
      { id: 1, type: 'Name', options}, 
      { id: 2, type: 'Data', options},
      { id: 3, type: 'Cidade', options},
      { id: 4, type: 'Estado', options},
      { id: 5, type: 'PMS', options},
    ],
}

然后我在渲染函数上调用表格组件

 <Table listHotels={listHotels} toggleList={this.toggleList} selectFilter={selectFilter}></Table>

Table组件上,我处于跟踪过滤器选择选项的状态,如下所示(状态,pms,状态...):

state = {
    page: 0,
    rowsPerPage: 5,
    query: '',
    filter: [],
    status: null,
    pms: null,
    state: null,
    city: null,
    name: null,
    isLoading: false
  }; 

无论何时选择该选项,我都会创建一个API调用以访问后端并响应一些数据以填充该州的filter属性。

componentDidUpdate(prevProps, prevState){
    const { status, pms, state, city, page, rowsPerPage } = this.state;

    const filterOptions = [];

    if (status !== null){
      filterOptions.push({name: "status", value: status});
    }

    if (pms !== null){
      filterOptions.push({name: "pms", value: pms});
    }

    if (state !== null){
      filterOptions.push({name: "estado", value: state});
    }

    if (city !== null){
      filterOptions.push({name: "cidade", value: city});
    }

    if(filterOptions.length !== 0){
      const url = createAPICall(filterOptions, page, rowsPerPage);
      //call api and set it to the filter property
    }

但是,组件当前的方式不可重用。如果要使用其他过滤器创建另一个表,则必须更改状态以保存过滤器变量并创建API网址。

如何使它更具动态性?

1 个答案:

答案 0 :(得分:2)

假设您想使过滤器类型更灵活。问题的一部分是您在状态和表中手动列出它们。首先将您的过滤器类型绑定到一个对象中,以便从主对象传递出去(或从selectFilter中提取它们)。

设置状态时,请设置filters: {...parse filters here...}

接下来在componentDidUpdate中,您不想手动列出每个if语句,而是要遍历过滤器obj定义,在每个循环中为每个obj键添加一个if。在表单/表中更新值时,将键值推入状态对象中,而不是像现在这样将单个值推入。

   const { status, pms, state, city, page, rowsPerPage } = this.state;

看起来更像

   const { filters, page, rowsPerPage } = this.state;