如何使用搜索框过滤产品?

时间:2018-09-10 09:38:26

标签: javascript reactjs

我在要根据搜索字段输入的值显示产品的代码之间插入了代码。对于每个按键,都必须检查产品是否可用。如果可用,它必须显示。有人可以帮我吗?

enter codeclass DashView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [],
      results: []
    };
    this.getSearchInfo = this.getSearchInfo.bind(this);
  }
  componentDidMount() {
    // const { isChecked } = this.state;
    let apiUrl = ` https://api.myjson.com/bins/4xc0c`;
    axios.get(apiUrl).then(res => {
      // console.log(res.data.products);
      this.setState({
        products: res.data.products
      });
    });
  }
  getSearchInfo = item => {
    const { products, results } = this.state;
    console.log(products);
    if (item.length > 0) {
      for (let i = 0; i < products.length; i++) {
        // console.log(products[i].title);
        if (products[i].title === item) {
          results.push(products[i]);
        }
      }
    }
    console.log(results);
  };
}

1 个答案:

答案 0 :(得分:0)

componentDidMount() {
    let apiUrl = ` https://api.myjson.com/bins/4xc0c`;
    axios.get(apiUrl).then(res => {
        // console.log(res.data.products);
        this.setState({
            products: res.data.products,
        }, () => {this.getSearchInfo('');});
    });
}

getSearchInfo = (item) => {
    const { products, results } = this.state;
    if (item && item.length > 0) {
        results = products.filter(prod => {
            if(prod.title.indexOf(item) > -1) {
                return prod;
            }
        });
    } else {
        Object.assign(results, products);
    }
    this.setState({
        ...this.state,
        results
    })
}

您可以尝试吗?