如何使用循环显示数组的键和值(this.state.filtered)?

时间:2019-01-06 11:02:58

标签: javascript html

我正在使用React和Vanilla JS。 Demo

主要代码

import React from "react";
import { render } from "react-dom";
import { makeData } from "./Utils";

import Select from "react-select";
import "react-select/dist/react-select.css";

// Import React Table
import ReactTable from "react-table";
import "react-table/react-table.css";

import jsondata from "./sample";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      // data: makeData(),
      data: jsondata,
      filtered: [],
      select2: null,
      select3: null
    };
    this.uniqueOptions = this.uniqueOptions.bind(this);
  }

  onFilteredChangeCustom(value, accessor) {
    console.log("The value is " + value);
    let filtered = this.state.filtered;
    console.log("the filtered items" + JSON.stringify(this.state.filtered));
    let insertNewFilter = 1;

    if (filtered.length) {
      console.log("filtered.length " + filtered.length);
      filtered.forEach((filter, i) => {
        if (filter["id"] === accessor) {
          if (value === "" || !value.length) filtered.splice(i, 1);
          else filter["value"] = value;

          insertNewFilter = 0;
        }
      });
    }

    if (insertNewFilter) {
      filtered.push({ id: accessor, value: value });
    }

    this.setState({ filtered: filtered });

    console.log("The filtered data is " + JSON.stringify(this.state.filtered));
  }

  uniqueOptions = (objectsArray, objectKey) => {
    var a = objectsArray.map((o, i) => {
      return o[objectKey];
    });

    return a.filter(function(i, index) {
      return a.indexOf(i) >= index;
    });
  };

  render() {
    const { data } = this.state;

    let first_names = null;
    let last_names = null;
    let first_names_label = null;
    let last_names_label = null;
    if (this.state.filtered.length == 1) {
      if (this.state.filtered[0].id == "firstName") {
        first_names_label = "First Name:";
      } else {
        first_names_label = "Last Name:";
      }
      first_names = this.state.filtered[0].value.map(name => <p>{name}</p>);
    } else if (this.state.filtered.length == 2) {
      first_names_label = "First Name:";
      first_names = this.state.filtered[0].value.map(name => <p>{name}</p>);
      last_names_label = "Last Name:";
      last_names = this.state.filtered[1].value.map(name => <p>{name}</p>);
    }

    return (
      <div>
        <pre>
          {first_names_label}
          {first_names}
          {last_names_label}
          {last_names}
        </pre>
        <br />
        <br />
        Extern Select2 :{" "}
        <Select
          style={{ width: "50%", marginBottom: "20px" }}
          onChange={entry => {
            this.setState({ select2: entry });
            this.onFilteredChangeCustom(
              entry.map(o => {
                return o.value;
              }),
              "firstName"
            );
          }}
          value={this.state.select2}
          multi={true}
          options={this.uniqueOptions(this.state.data, "firstName").map(
            (name, i) => {
              return { id: i, value: name, label: name };
            }
          )}
        />
        Extern Select3 :{" "}
        <Select
          style={{ width: "50%", marginBottom: "20px" }}
          onChange={entry => {
            this.setState({ select3: entry });
            this.onFilteredChangeCustom(
              entry.map(o => {
                return o.value;
              }),
              "lastName"
            );
          }}
          value={this.state.select3}
          multi={true}
          options={this.uniqueOptions(this.state.data, "lastName").map(
            (name, i) => {
              return { id: i, value: name, label: name };
            }
          )}
        />
        <ReactTable
          data={data}
          filtered={this.state.filtered}
          onFilteredChange={(filtered, column, value) => {
            this.onFilteredChangeCustom(value, column.id || column.accessor);
          }}
          defaultFilterMethod={(filter, row, column) => {
            const id = filter.pivotId || filter.id;
            if (typeof filter.value === "object") {
              return row[id] !== undefined
                ? filter.value.indexOf(row[id]) > -1
                : true;
            } else {
              return row[id] !== undefined
                ? String(row[id]).indexOf(filter.value) > -1
                : true;
            }
          }}
          columns={[
            {
              Header: "Name",
              columns: [
                {
                  Header: "First Name",
                  accessor: "firstName"
                },
                {
                  Header: "Last Name",
                  id: "lastName",
                  accessor: d => d.lastName
                }
              ]
            },
            {
              Header: "Info",
              columns: [
                {
                  Header: "Age",
                  accessor: "age"
                }
              ]
            }
          ]}
          defaultPageSize={10}
          className="-striped -highlight"
        />
        <br />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

我有一个已过滤状态变量(this.state.filtered),该变量具有下拉菜单中的所有已过滤项。

我想显示过滤后的状态变量

<div>
<div>id: val0,val1 (and a cross button to remove this filter)</div>
<div>id: val0,val1 (and a cross button to remove this filter)</div> .... so on
</div>

我已经能够对2个变量执行此操作。但是将来我会有10到15个下拉菜单。这就是为什么我想使用循环显示。该怎么做?

演示中的代码没有循环,我想使其成为通用代码,该代码可以显示this.state.filtered的所有键值对。如果没有循环,当我有大量下拉菜单时,我将无法使用此功能。值也应以逗号分隔。我也不想使渲染函数又脏又臭。我想基本上调用一个将显示键和值的函数

0 个答案:

没有答案