如何在 React 中使用函数过滤项目

How to filter items using function in React

我正在使用 React select 按类别过滤我的电影,但我的功能不起作用,当我单击要过滤的元素时,它会删除 UI 上的所有电影

这是我的过滤器组件:

import React from 'react';
import Select from 'react-select';


    const CategoriesFilter = ({categories, filterMovie}) => {
        const options = categories.map((c) => ({ value: c, label: c }));
        
        return (
        <div>  
        <Select
        className="select-option"
        options={options}
        placeholder={"type something"}
        onChange={filterMovie}
        />
        </div>
          
        )
    }
    
    export default CategoriesFilter;

这是我的应用程序 js 中的过滤函数和状态

const [moviesList, setMoviesList] = useState(MoviesData);
     const filterMovie = (category) => {
        const filterMovie = MoviesData.filter((movie)=> movie.category === category);
        setMoviesList(filterMovie);
      }

您认为问题出在哪里?

谢谢大家

问题是您的回调函数正在接收您设置到 Select

中的对象
const options = categories.map((c) => ({ value: c, label: c }));

和你比较

const filterMovie = MoviesData.filter((movie)=> movie.category === category);

应该是

const filterMovie = MoviesData.filter((movie)=> movie.category === category.value);

检查:

const CategoriesFilter = ({ categories, filterMovie }) => {
  const options = categories.map((c) => ({ value: c, label: c }));

  return (
    <div>
      <Select
        className="select-option"
        options={options}
        placeholder={"type something"}
        onChange={filterMovie}
      />
    </div>
  );
};

const MoviesData = [
  {
    title: "Foo",
    category: "horror"
  }
];

export default function App() {
  const [moviesList, setMoviesList] = useState(MoviesData);
  const filterMovie = (category) => {
    console.log(category);
    const filterMovie = MoviesData.filter(
      (movie) => movie.category === category.value
    );
    setMoviesList(filterMovie);
  };
  console.log(moviesList);
  return (
    <div className="App">
      <CategoriesFilter
        categories={["horror", "action"]}
        filterMovie={filterMovie}
      />
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}