简体   繁体   English

反应 - 为什么我的过滤方法不起作用

[英]REACT - Why isnt my Filter Method Working

Im trying to simply create a search and results feature for an app.我试图简单地为应用程序创建搜索和结果功能。 The value of the input should reflect the components listed in the CardList Array.输入值应反映 CardList 数组中列出的组件。 The filter doesn't seem to update the CardList.过滤器似乎没有更新 CardList。 I've logged steps along the way and I've come to the conclusion that its the filter I set up.我已经记录了沿途的步骤,我得出的结论是它是我设置的过滤器。 I cant seem to figure out why it wont filter the list.我似乎无法弄清楚为什么它不会过滤列表。

import React, {Component} from 'react';
import CardList from './CardList';
import {robots} from './robots';
import './index.css';

class App extends Component {
  constructor() {
    super()
    this.state = {
      robots: robots,
      searchfield: ''
    }
  }

  onSearchChange = (event) => {
    this.setState({ searchfield: event.target.value });
  }

  render() {
    const filteredRobots = this.state.robots.filter(robot => {
      return robot.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
    });

    return (
      <div className="appAlign">
        <h1 className="appTitle">RoboFriends</h1>
        <input
          className="searchBox"
          type="search"
          placeholder="Search Robots"
          onChange={this.onSearchChange}
        />
        <CardList robots={filteredRobots} />
      </div>
    );
  }

  }


export default App;

The error is not caused by the filter function as I have tested it and it works.该错误不是由filter function 引起的,因为我已经对其进行了测试并且可以正常工作。 It most probably lies with the robots data-set.它很可能与robots数据集有关。 I have slightly modified the filter function here.我在这里稍微修改了filter function。

import React, { Component } from "react";
import CardList from "./CardList";
import { robots } from "./robots";

class App extends Component {
  constructor() {
    super();
    this.state = {
      robots: robots,
      searchfield: ""
    };
  }

  onSearchChange = event => {
    this.setState({ searchfield: event.target.value });
  };

  render() {
    const filteredRobots = this.state.robots.filter(robot =>
      robot.name.toLowerCase().includes(this.state.searchfield.toLowerCase())
    );

    return (
      <div className="appAlign">
        <h1 className="appTitle">RoboFriends</h1>
        <input
          className="searchBox"
          type="search"
          placeholder="Search Robots"
          onChange={this.onSearchChange}
        />
        <CardList robots={filteredRobots} />
      </div>
    );
  }
}

export default App;

I have made a sandbox with your code which has a sample robots data and a Card that renders the filtered data-set.我用您的代码制作了一个沙箱,其中包含一个示例robots数据和一个呈现过滤数据集的Card Take a look.看一看。

编辑 magic-bush-os9wz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM