反应中的搜索功能出现问题

时间:2020-02-25 04:41:11

标签: reactjs

我的搜索功能有问题。我尝试使用过滤器,但结果与预期不符。我使用过滤器在handleClickSearch中过滤出了合格的video.name并将onClick事件分配给了Search按钮,但这似乎是错误的。 这是我的代码

import SearchBar from "../components/SearchBar";
import VideoDetail from "../components/VideoDetail";
import fetch from "isomorphic-unfetch";
import Head from "next/head";

const Index = ({ data }) => {
  const [videos, setVideos] = useState([]);
  const [numberVideo, setNumberVideo] = useState(2);
  const [keywords, setKeywords] = useState("");

  const loadMore = () => {
    setNumberVideo(numberVideo + 2);
  };

  const handleChange = e => {
    setKeywords(e.target.value);
  };

  const handleClickSearch = () => {
    setVideos(
      data.filter(video => {
        return video.name.toLowerCase().indexOf(keywords) !== -1;
      })
    );
  };

  useEffect(() => {
    setVideos(data);
  });

  return (
    <>
      <Head>
        <title>App Search Video</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <link rel="stylesheet" type="text/css" href="/css/style.css" />
      </Head>
      <h1>App search video</h1>
      <SearchBar
        handleChange={handleChange}
        handleClickSearch={handleClickSearch}
      />

      <div className="wrap-content">
        {videos.slice(0, numberVideo).map((video, index) => {
          return (
            <div key={index} className="content">
              <div className="section-left">
                <img src={video.img} />
                <span>{video.time}</span>
              </div>
              <div className="section-right">
                <h2>
                  <VideoDetail video={video} />
                </h2>
                <p>{video.description}</p>
              </div>
            </div>
          );
        })}
        {numberVideo < videos.length && (
          <button onClick={loadMore} type="button" className="load-more">
            Load more
          </button>
        )}
      </div>
    </>
  );
};

Index.getInitialProps = async function() {
  const res = await fetch("http://localhost:4000/videoList");
  const data = await res.json();

  return {
    data
  };
};

export default Index;

我是否曾经误解过这个问题?你能帮助我吗?谢谢。

1 个答案:

答案 0 :(得分:0)

在搜索中尝试这种逻辑

{data.slice(0, numberVideo).map((video, index) => {
       if(video.name.toLowerCase().includes(keywords.toLowerCase())){
          return (
            <div key={index} className="content">
              <div className="section-left">
                <img src={video.img} />
                <span>{video.time}</span>
              </div>
              <div className="section-right">
                <h2>
                  <VideoDetail video={video} />
                </h2>
                <p>{video.description}</p>
              </div>
            </div>
          );
       }
       else null
        })}

使用此逻辑,您不需要使用过滤器和额外的数组列表