我有一个电子商务网站和一个过滤器,可以根据品牌过滤产品。
我的减速器:
const INITIAL_STATE = {
products: [
{
id: 1,
type: "joggers",
category: "pant",
gender: "female",
color: "Green",
brand: "Wrangler",
name: "Camo Print Joggers Pants",
},
{
id: 2,
type: "joggers",
category: "pant",
gender: "male",
color: "Green",
brand: "US Polo Assn",
name: "Camoflage Print Slim Fit Jogger Pants",
},
],
brands: ["Wrangler", "Vermo Moda", "AJIO", "HRX", "Nike", "Puma", "US Polo Assn", "Levis", "The Roadster", "H & M", "Jack & Jones"],
refinedProducts: [],
};
const shopReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case actionTypes.REFINE_BY_BRAND:
if (action.payload.boolVal === true) {
INITIAL_STATE.products.forEach((element) => {
if(element.brand === action.payload.brand){
state.refinedProducts.push(element);
}
});
return {
...state,
products: state.refinedProducts,
};
}
else{
INITIAL_STATE.products.forEach((element) => {
if(element.brand === action.payload.brand){
state.refinedProducts.pop(element);
}
});
return {
...state,
products: state.refinedProducts,
};
}
default:
return state;
}
};
export default shopReducer;
我的REACT组件代码:
import React from 'react';
import "./crownFashionStore.css"
import { connect } from "react-redux";
import { refineByFemale, refineByMale, refineByBrand, refineByColor } from "../../redux/shop/shop-actions";
import Product from '../product/Product';
function CrownFashionStore(props) {
console.log(props);
return (
<div className="shop-container">
<div className="brands">
<p>Brands</p>
{props.brands.map((brand, index) => {
return (
<div key={index} className="filter">
<input
value={brand}
onClick={(e) => {
const brand = e.target.value;
const boolVal = e.target.checked;
props.refineByBrand(brand, boolVal);
console.log(props);
}}
type="checkbox"
/>
<label htmlFor="">{brand}</label>
</div>
);
})}
</div>
<div className="body-right">
{props.products.map((product) => {
return <Product key={product.id} data={product} />; //<-- triggers only once
})}
</div>
</div>
);
};
const mapStateToProps = (state) => {
return {
products: state.shop.products,
brands: state.shop.brands,
refinedProducts: state.shop.refinedProducts,
};
};
const mapDispatchToProps = (dispatch) => {
return {
refineByBrand: (brand, boolVal) => dispatch(refineByBrand(brand, boolVal)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(CrownFashionStore);
每当我点击用于按品牌过滤产品的输入复选框时,映射功能就会被触发,并在屏幕上呈现所需的产品。但当我点击其他品牌时,状态(产品(会发生相应的变化,但问题是Map函数不会第二次触发,因此无法输出所需的结果。有人能帮我找出我在这里犯的错误吗?
将产品更改为组件中的精化产品,并将减速器更改为下面的代码
case actionTypes.REFINE_BY_BRAND:
if (action.payload.boolVal === true) {
const filteredProduct = Array.from(state.products);
return {
...state,
refinedProducts: filteredProduct.filter(a=>a.brand === action.payload.brand),
};
}
else{
const filteredProduct = Array.from(state.refinedProducts);
return {
...state,
refinedProducts: filteredProduct.filter(a=>a.brand !== action.payload.brand),
};
}