简体   繁体   English

在 ReactJs 代码中需要帮助 - 过滤器按钮

[英]Need help in ReactJs code - filter button

I'm trying to create a filter button by ReactJs, spent a lot of times but still do not know why it's doesn't work Here are my codePen: https://codepen.io/tinproht123/pen/gOxeWpy?editors=0110我正在尝试通过ReactJs创建一个过滤器按钮,花了很多时间但仍然不知道为什么它不起作用这是我的codePen: https://codepen.io/tinproht123/pen/gOxeWpy?editors=01

  const [menuItems, setMenuItems] = React.useState(menu);
  const [categories, setCategories] = React.useState(allCategories);
  
  const filterItems = (category) =>{
    if(category === 'all'){
      setMenuItems(menu);
      return;
    }
    const newItems = menu.filter((item)=> item.category === category)
    setMenuItems(newItems);
  }
  
  return(
    <section className='container'>
      <div className='title'>
        <h1>Our menu</h1>
      </div>
      <Categories categories={categories} filterItems={filterItems}/>
      <Menu menu={menuItems}/>
    </section>
  )
}~~~

I checked your code and the problem isn't in the part that you showed to us.我检查了您的代码,问题不在您向我们展示的部分。 Instead please check your codes 103th line, on codepen.相反,请在 codepen 上检查您的代码第 103 行。 Your code seems like that:你的代码看起来像这样:

const Menu = () =>{
  return(
    <div className='menu-container'>
      {menu.map((menuItem) => {
      ....

Be careful to the first line, since your all menu items stays in menu variable, even though you made correct filtering, you're printing the result for all menus.请注意第一行,因为您的所有菜单项都保留在menu变量中,即使您进行了正确的过滤,您也会打印all菜单的结果。

I saw that you're sending a prop to a <Menu menu={menuItems}>.... but you're not using it.我看到您正在向<Menu menu={menuItems}>....发送一个道具,但您没有使用它。 To use this prop you should add a parameter to your Menu function;要使用这个道具,你应该在你的Menu function 中添加一个参数;

const Menu = ({menu}) =>{
  return(
    <div className='menu-container'>
      {menu.map((menuItem) => {

Just like above.就像上面一样。

In the Menu component, you're not passing any props but just rendering the const value declared on top of the file.Menu组件中,您没有传递任何道具,而只是呈现在文件顶部声明的 const 值。

You're filtering exactly by categories but rendering is not showing the updated one.您正在按类别进行过滤,但渲染未显示更新的类别。 :) :)

在此处输入图像描述

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

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