简体   繁体   English

React 中的搜索过滤器在尝试使用 state 挂钩时出错

[英]search filter in React giving error while trying to use state hooks

  • I am try to add search feature to an existing lists of robot names.我正在尝试将搜索功能添加到现有的机器人名称列表中。
  • In order to do so I am trying to useState hooks.为此,我正在尝试使用状态挂钩。 I have an App component and Header component which has the input tag for search field.我有一个 App 组件和 Header 组件,它具有搜索字段的输入标签。
  • Error I am getting is 'InputEvent' is assigned a value but never used.我得到的错误是“InputEvent”被分配了一个值但从未使用过。 Below is the code for App component (main component).下面是 App 组件(主要组件)的代码。
import "./App.css";
import Header from "./Header";
import Robo from "./Robo";
import { robots } from "./robots";
import { useState } from "react";

function App() {
  const [query, setQuery] = useState("");
  const InputEvent = (e) => {
    const data = e.target.value;
    setQuery(data);

    const extraction = robots
      .filter((curElem, index) =>
        robots[index].name.toLowerCase().includes(query)
      )
      .map((curElem, index) => {
        return (
          <Robo
            key={robots[index].id}
            id={robots[index].id}
            name={robots[index].name}
            email={robots[index].email}
          />
        );
      });
    return (
      <div className="App">
        <Header query={query} InputEvent={InputEvent} />
        <div className="robo-friends-container">{extraction};</div>
      </div>
    );
  };
}
export default App;

Child component子组件

import React from "react";
import "./header.css";

const Header = ({ query, InputEvent }) => {
  return (
    <>
      <div className="headerText">ROBO FRIENDS</div>
      <div>
        <input
          type="text"
          id="lname"
          name="lname"
          placeholder="Search"
          value={query}
          onChange={InputEvent}
        />
      </div>
    </>
  );
};

export default Header;

Here is my answer in stackblitz app这是我在 stackblitz 应用程序中的回答

https://stackblitz.com/edit/stackoverflow-robots-filter?file=App.tsx,Robo.tsx,Header.tsx,robots.ts https://stackblitz.com/edit/stackoverflow-robots-filter?file=App.tsx,Robo.tsx,Header.tsx,robots.ts

I have altered the code a bit.. you can fork the project and play with it..我稍微修改了代码..你可以 fork 项目并使用它..

You can add debounce option to your input, which prevents unwanted re-renders您可以为输入添加去抖动选项,以防止不需要的重新渲染

Adding the changes:添加更改:

function App() {
  const [query, setQuery] = useState(undefined);
  const [filteredRobots, setFilteredRobots] = useState([]);

  useEffect(() => {
    console.log(query);

    const filteredRobots = robots.filter((robot) => {
      return robot.name.includes(query);
    });

    if (filteredRobots.length) {
      setFilteredRobots(filteredRobots);
    }
  }, [query]);

  const onQueryChange = (e) => {
    const data = e.target.value;
    setQuery(data);
  };

  const renderRobots = () => {
    if (!query || !query.length) {
      return <p>{'Search to find Robots'}</p>;
    }

    if (filteredRobots && filteredRobots.length && query && query.length) {
      return filteredRobots.map((filteredRobot) => (
        <Robo
          key={filteredRobot.id} //id is unique key in your data
          name={filteredRobot.name}
          id={filteredRobot.id}
          email={filteredRobot.email}
        />
      ));
    }

    return <p>{'No Robots Found'}</p>;
  };

  return (
    <div className="App">
      <Header query={query} InputEvent={onQueryChange} />
      {renderRobots()}
    </div>
  );
}

Problems in your code:您的代码中的问题:

  1. Const InputChange is a function that can be used as prop for any React component.. but you have added InputChange inside the InputChange named function itself which is incorrect Const InputChange是一个 function,可以用作任何 React 组件的道具。但是您在名为 function 本身的InputChange中添加了InputChange ,这是不正确的
  2. Extraction is a jsx variable which is created from Array.filter .. on each item, filter passes a item[index] to the filter function.. you dont want to do robots[index].name.toLowerCase().includes(query) .. instead you could have done curElem.name.toLowerCase().includes(query) and same applies for Array.map Extraction是一个 jsx 变量,它是从Array.filter创建的。在每个项目上,过滤器将项目 [index] 传递给过滤器 function .. 你不想做robots[index].name.toLowerCase().includes(query) .. 相反,您可以完成curElem.name.toLowerCase().includes(query)并且同样适用于Array.map

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

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