javascript-创建一个函数来对表React,JSX进行排序

前端之家收集整理的这篇文章主要介绍了javascript-创建一个函数来对表React,JSX进行排序 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图找出一种根据sortBy和order状态对行数组进行排序的方法.我目前有一个handleSort函数,该函数将捕获列名并将其设置为sortBy状态,并通过“ asc”或“ desc”来切换顺序,但是现在我试图弄清楚如何根据sortBy操作行和秩序状态.我相信可以创建长时间的条件渲染,但想知道有人会以更简单的方式来丢失我吗?感谢您的帮助.

state = {
columnHeaders: [
  "Meat","Protein (g)","Calories (cal)","Carbohydrates (g)","Fat (g)"
 ],rows: [
  ["chicken breast","25","200","37","8"],["fried chicken","45","450","21","16"],["baked fish","15","250","30","9"]
    ],sortedBy: "",order: "desc",query: "all",error: false
    };

  handleClose = () => {
  this.setState({ error: !this.state.error });
  };

  handleQuery = keyword => {
  this.setState({
  query: keyword
   });
   if (keyword === "chicken") {
   this.setState({
    rows: this.state.rows.filter(row => row[0].includes("chicken"))
   });
   } else if (keyword === "fish") {
    this.setState({
    rows: this.state.rows.filter(row => row[0].includes("fish"))
   });
   } else if (keyword === "beef") {
    this.setState({
    rows: this.state.rows.filter(row => row[0].includes("beef"))
    });
    } else {
    this.setState({
    error: true
     });
     }
     };

 handleSort = header => {
 this.setState(state => ({
  sortedBy: header,order: state.sortedBy === header ? invertDirection[state.order] : 
   "asc"
 }));
 };

  render() {
  const { columnHeaders,rows } = this.state;

return (
  <div className="App mt-3">
    <AlertDialogSlide
      open={this.state.error}
      handleClose={this.handleClose}
    />
    <Search handleQuery={this.handleQuery} />
    <Paper className="mt-3">
      <Header />
      <Table>
        <TableHead>
          <TableRow>
            {columnHeaders.map((header,i) => (
              <TableHeader
                header={header}
                key={`th-${i}`}
                handleSort={this.handleSort.bind(this,header)}
              />
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row,i) => (
            <TableRow key={`thc-${i}`}>
              <TableItem row={row} />
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </Paper>
  </div>
   );
  }
  } 
最佳答案
首先,您应该将原始数据和过滤后的数据保存在不同的位置,例如原始数据来自道具,过滤后的数据处于状态.因为如果您覆盖数据(像现在这样),您将无法进行在搜索“鸡”之后搜索“鱼”,因为数据被过滤为仅包括“鸡”条目-所有“鱼”条目已删除且不再可访问.

其次,如果要根据旧状态设置新状态,则应始终向setState函数(check out this link)提供函数而不是状态对象.

第三,您可以直接使用关键字进行过滤,而不必在handleQuery中使用if-else块.

现在到您的问题:
您可以使用以下代码段对行进行排序和过滤:

const { rows } = this.props; // assuming the original data comes from the props!
const { query,sortedBy,order } = this.state;

// filter the data (only if query is not "all"
const newRows = query === "all" ? rows : rows.filter(row => row[0].includes(query));

const sortedRows = sortedBy === "" ? newRows : newRows.sort((a,b) => {
  const valueA = a[sortedBy]; // get the row to sort by
  const valueB = b[sortedBy]; // get the row to sort by

  let sortedValue = 0;

  if (valueA < valueB) {
    sortedValue = -1;
  }
  else if (valueA > valueB) {
    sortedValue = 1;
  }

  if (order === "desc") {
    sortedValue *= -1; // if descending order,turn around the sort order
  }

  return sortedValue;
});

this.setState({rows: sortedRows});

猜你在找的JavaScript相关文章