我正在尝试通过构建电子商务网站来练习和学习 mern 堆栈,以便尽可能多地一起使用技能。我想问一下你们如何过滤产品,例如,如果我有一个 cpus/处理器页面,我想根据品牌(amd,intel)过滤它们。到目前为止,我所做的有点有效但并不完全正确的是:
const [cpus, setCpus] = useState([]); // here i save the cpus i get from the database
const [defaultData, setDefaultData] = useState([]); //here i keep a copy of the original
useEffect(() => {
const fetchData = async () => {
const { data } = await axios.get(cpuUrl);
setCpus(data);
setDefaultData(data);
};
fetchData();
}, []);
function filterProducts(event) {
const currentState = [...cpus];
let newState = currentState;
if (event.target.checked === true && event.target.name === "AMD") {
newState = currentState.filter((cpu) => cpu.subcategory.includes("AMD"));
setCpus(newState);
} else if (event.target.checked === true && event.target.name === "Intel") {
newState = currentState.filter((cpu) =>
cpu.subcategory.includes("Intel")
);
setCpus(newState);
} else {
setCpus(defaultData);
}
}
这是过滤器组件:
<Filters filterBrand1="AMD" filterBrand2="Intel" filterProducts={filterProducts} />
这是过滤器组件的内容:
<div className="filter-contents">
<div>
<input
name="AMD"
type="checkbox"
className="checkbox"
onChange={props.filterProducts}
></input>
<label className="filter-label">{props.filterBrand1}</label>
</div>
<div>
<input
name="Intel"
type="checkbox"
className="checkbox"
onChange={props.filterProducts}
></input>
<label className="filter-label">{props.filterBrand2}</label>
</div>
</div>
那么现在对于我的问题,你们是否会为每个品牌创建一个不同的 api 端点,比如 amd 从 amd api 端点获取 amd cpus 以及对于 intel 也是如此,或者你们会使用过滤器功能做一些类似于我的事情吗?并每次更改 CPU 的状态以显示正确的数据。最好的方法是什么,如果你能解释一下为什么。 也随时指出任何编码错误,我想学习输入好的代码。提前致谢!