javascript 如何在react-redux中显示状态更改后的列表项

hjzp0vay  于 2023-02-15  发布在  Java
关注(0)|答案(1)|浏览(116)

我有一个菜单栏,显示我的商店类别。当我点击一个类别,该类别的产品列表应该显示在我的商店组件(我也使用redux库)。它第一次正确工作,但当我点击另一个类别的状态变化和过滤器产品更新太多,但他们不显示在我的商店组件。我必须点击一个按钮在页面上显示更新的列表在商店组件。如何在更新后立即显示它们?
App.jsx

<Menubar/>
<Routes>
  <Route path='/shopping' element={<Shop />}></Route>
</Routes>

Menubar.jsx

export default function MenuBar() {
  const products = useSelector(state=>state.products);
  const navigate = useNavigate();
 
  const getCategory = (e) => {
    let category = e.target.innerText;
    dispatch(filterProByCategory(products, category));
    navigate('/shopping');
  }

  return (
    <>
      <ul>
        <li onClick={(e)=>getCategory(e)}>
          Fashion
        </li>
      </ul>
    </>
  )
}

Shop.jsx

export default function Shop() {
  const products = useSelector(state => state.filters.filterProducts);
  const [filterProducts, setFilterproducts] = useState(products);

  return (
    <>
      <Grid item xs={12} md={8} dir='rtl'>
        <Card sx={{ minWidth: 275 }}>
          <CardContent>
            {/*  */}
            <Grid container spacing={1}>
              {filterProducts && filterProducts.map((product, index) => (
                <Grid item xs={12} md={4}>
                  <ProductCard product={product} key={index} />
                </Grid>
              ))}
            </Grid>
    </>
  )
}
lmvvr0a8

lmvvr0a81#

只需使用products的直接结果,而不是使用它通过useState创建另一个状态变量filteredProducts

export default function Shop() {
  const products = useSelector(state=>state.filters.filterProducts);
//  const [filterProducts , setFilterproducts] = useState (products);
  return (
  <>
      <Grid item  xs={12} md={8} dir='rtl'>
                <Card sx={{ minWidth: 275 }}>
                <CardContent>
                  {/*  */}
                  <Grid container spacing={1}>
                 
                  {products && products.map((product , index)=>(
                     <Grid item xs={12} md={4}>
                    <ProductCard product={product} key={index}/>
                    </Grid>
                  ))}
                </Grid>
  </>
 )
}

相关问题