簡體   English   中英

反應 - 為什么我的過濾方法不起作用

[英]REACT - Why isnt my Filter Method Working

我試圖簡單地為應用程序創建搜索和結果功能。 輸入值應反映 CardList 數組中列出的組件。 過濾器似乎沒有更新 CardList。 我已經記錄了沿途的步驟,我得出的結論是它是我設置的過濾器。 我似乎無法弄清楚為什么它不會過濾列表。

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;

該錯誤不是由filter function 引起的,因為我已經對其進行了測試並且可以正常工作。 它很可能與robots數據集有關。 我在這里稍微修改了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;

我用您的代碼制作了一個沙箱,其中包含一個示例robots數據和一個呈現過濾數據集的Card 看一看。

編輯 magic-bush-os9wz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM