【问题标题】:How to use Filter with ReactJS to prevent duplicates in an array from being displayed如何使用带有 ReactJS 的过滤器来防止显示数组中的重复项
【发布时间】:2018-10-17 12:48:27
【问题描述】:

我有一个包含三个下拉列表的 ReactJS 页面,其中两个下拉列表显示重复值。这些值是从 json 文件中使用的。我研究了使用过滤器删除重复项,但我不确定在使用 React JS 和 Fetch 时如何将它应用到我的数组中。 我创建了一个使用过滤器方法的函数,但我不确定如何将它实现到数据上:[],它包含从 json 文件中消耗的数据。这是示例 json 文件:https://api.myjson.com/bins/b1i6q

这是我的代码

import React, { Component } from "react";

class Ast extends Component {
  constructor() {
    super();
    this.state = {
      data: [],
      cfmRateFactor: "10"
    };
  } //end constructor

  change = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  }; //end change

     removeDups(array) {
    return array.reduce((result, elem) => {
        if (!result.some((e) => e.clientName === elem.clientName)) {
            result.push(elem);
        }
        return result;
    } , []);
}

  componentWillMount() {
    fetch("https://api.myjson.com/bins/b1i6q", {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-type": "application/json"
      }
      /*body: JSON.stringify({
            username: '{userName}',
            password: '{password}'
        })*/
    }) /*end fetch */
      .then(results => results.json())
      .then(data => this.setState({ data: data }));
  } //end life cycle

  render() {
    console.log(this.state.data);
    return (
      <div>
        <div className="container">
          <div className="astContainer">
            <form>
              <div>
                <h2>Memeber Selection:</h2>

                {["clientName", "siteName", "segmentName"].map(key => (
                  <div className="dropdown-padding">
                    <select key={key} className="custom-select">
                      {this.state.data.map(({ [key]: value }) => (
                        <option key={value}>{value}</option>
                      ))}
                    </select>
                  </div>
                ))}
              </div>

              <div className="txt_cfm">
                <label for="example-text-input">Modify CFM Rate Factor:</label>
                <input
                  class="form-control"
                  type="textbox"
                  id="cfmRateFactor"
                  name="cfmRateFactor"
                  value={this.state.cfmRateFactor}
                  onChange={e => this.change(e)}
                />
              </div>
              <div>
                <div>
                  <button type="submit" className="btn btn-primary">
                    Submit
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    );
  }
}

export default Ast;

我能得到一些帮助吗?我对使用 React JS 还是很陌生。

【问题讨论】:

    标签: json reactjs filter fetch


    【解决方案1】:

    您可以使用Map,它是一种用于保存键值对的数据结构。它将为您提供大数据的最佳性能。

    removeDuplicates(arr) {
      const map = new Map();
      arr.forEach(v => map.set(v.abc_buildingid, v)) // having `abc_buildingid` is always unique
      return [...map.values()];
    }
    
    
    // this hook is better to start fetching data than componentWillMount
    componentDidMount() {
        fetch("https://api.myjson.com/bins/b1i6q", {
          method: "GET",
          headers: {
            Accept: "application/json",
            "Content-type": "application/json"
          }
        })
        .then(results => results.json())
        .then(data => this.setState({ data: this.removeDuplicates(data) })); // use the defined method
    } //end life cycle
    

    【讨论】:

    • @user1724708 :)
    【解决方案2】:

    filter 不会解决您的问题。但是reduce 会。

    你可以有以下:

    function removeDups(array) {
        return array.reduce((result, elem) => {
            if (!result.some((e) => e.abc_buildingid === element.abc_buildingid)) {
                result.push(elem);
            }
            return result;
        } , []);
    }
    

    【讨论】:

    • 我修改了我的代码(见上文)下拉客户端名称是显示重复项的内容。好吧,当在实际的生产 json 文件中使用时,clientName 和 segmentName 下拉菜单都显示重复;我应用了修改,但仍然出现重复项。我究竟做错了什么?提前致谢
    猜你喜欢
    • 2021-01-29
    • 2020-01-24
    • 2019-05-06
    • 1970-01-01
    • 2020-03-07
    • 2020-12-10
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    相关资源
    最近更新 更多