如何为 .toLowerCase 定义字符串以使用多个搜索项进行过滤搜索

how to define string for .toLowerCase for filter search with multiple search items

我是 React 的新手,在定义一些东西时遇到了问题。我的目标是让过滤器搜索工作并通过 API 通过 JSON 进行过滤。控制台显示我输入的内容已被确认,但我一直收到未定义的错误,即使我认为它们已定义。

此外,由于这是一个可以找到名字或姓氏的搜索,我如何设置关键字以同时正确地查看两个单独的项目,即 data.students[0].firstNamedata.students[0].lastName在您键入时发送过滤后的结果?

这是我的:

const USERS = "https://api.hatchways.io/assessment/students";
export default function FilterSearch() {
  const [name, setName] = useState(" ");
  const [foundUsers, setFoundUsers] = useState([]);

  const filter = (keyword) => {
    setName(keyword); 
    if (!keyword || keyword !== " ") {
      setFoundUsers([]); 
    }
    axios.get(USERS).then((listStudents) => {
      console.log(listStudents);
      const results = listStudents.data.students.filter((keyword) => {
        return name.toLowerCase(keyword).startsWith(keyword.toLowerCase());
      });
      setFoundUsers(results);
    });
  };

  return (
    <div className="container">
      <form>
        <input
          type="search"
          value={name}
          onChange={(e) => {
            filter(e.target.value);
          }}
          className="input"
          placeholder="Filter"
        />
        ;
      </form>

      <div className="user-list">
        {foundUsers && foundUsers.length > 0 ? (
          foundUsers.map((name) => <StudentInfo name={name} />)
        ) : (
          <h1>No results found!</h1>
        )}
      </div>
    </div>
  );
}

理想情况下,这会将搜索结果提供给此 StudentInfo 组件:

export default function StudentInfo({ info }) {
  return (
    <div className="StudentInfo">
      <div className="row">
        <div className="col-md-3">
          <img
            src={info.pic}
            alt={info.firstName}
            width={200}
            className="img-fluid pics"
          />
          <hr />
        </div>
        <div className="col-md-9">
          <h1 className="name">
            {info.firstName} {info.lastName}
          </h1>
          <h2>Email: {info.email}</h2>
          <h2>Company: {info.company}</h2>
          <h2>Skill: {info.skill}</h2>
          <h2>Average: {info.grades[0]}</h2>
          <hr />
        </div>
      </div>
    </div>
  );
}

可供选择的学生名单已经列出;它只需要通过搜索栏进行过滤以指定特定条目。

为了确保我理解正确,您想过滤 USERS 并将其设置为 foundUsers?如果是这样...

const filter = (keyword) => {

    if (!keyword || keyword !== " ") {
      setFoundUsers([]); 
    }
    axios.get(USERS).then((listStudents) => {
      console.log(listStudents);
      const results = listStudents.data.students.filter((keyword) => {
        return name.toLowerCase(keyword).startsWith(keyword.toLowerCase());
      });
      const results = listStudents.data.students.filter((singleValueFromStudentArray, index, arrayItSelf) => {
      //This is a regex way to do it, but do what you like.
      let regex = new Regex(keyword, "gi") \ gi=global meaning whole word, caseInsensitive
      // Filter just returns a true of false value, and then results is only the true results. This will match every singleValueFromStudentArray that has every character in keyword. If keyword is S, sam, and steve will be true. If it's sa, steve will be false, and if keyword is sm, sam would also be true.
      return regex.test(singleValueFromStudentArray)
      })
      setFoundUsers(results);
    });
/// Set the new value *after* you've used the current one
    setName(keyword); 
  };

您将为用户列表应用搜索栏。但是,如果没有应用搜索怎么办。不需要显示可用列表吗?

每当输入搜索时,您都会触发一个 API 调用并从中过滤数据。我建议您为此向 debounce 申请。并出现你的错误。

const results = listStudents.data.students.filter((keyword) => {
  return name.toLowerCase(keyword).startsWith(keyword.toLowerCase());
});

在上面的代码中,keyword是一个学生对象,你不能在对象上应用toLowerCase()。您可以执行 keyword?.name(whatever the field) 并应用 toLowerCase().

我制作了一个带有 useMemo 挂钩的简单沙箱,并对学生列表应用了过滤。看看这个并根据您的要求修改您的代码。