简体   繁体   English

如何设置回原来的 state React.js

[英]How to set back to original state React.js

This is my codeSandbox Code https://codesandbox.io/s/bold-lederberg-d2h508?file=/src/Components/Products/Products.js这是我的代码沙盒代码https://codesandbox.io/s/bold-lederberg-d2h508?file=/src/Components/Products/Products.js

Once I click in "default" I want to have the items back to the original presentation please But I can not do it单击“默认”后,我希望将项目恢复为原始演示文稿,但我做不到

sorting by price is working but the default option is giving me problems按价格排序有效,但默认选项给我带来了问题


import React, { useState } from "react";
import Products from "./Components/Products/Products";
import SearchInput from "./Components/SearchInput/SearchInput";
import data from "./utils/data";

const App = () => {
  const [searchValue, setSearchValue] = useState("");
  const [productsInfo, setProductsInfo] = useState([]);

  const handleChange = (e) => {
    setSearchValue(e.target.value);
  };

  const selectedChangeFilter = (e) => {
    const { value } = e.target;
    if (value === "sporting goods") {
      const sportingGoods = data.filter(
        (product) => product.category === "Sporting Goods"
      );
      setProductsInfo(sportingGoods);
    }
    if (value === "electronics") {
      const electronicsGoods = data.filter(
        (product) => product.category === "Electronics"
      );
      setProductsInfo(electronicsGoods);
    }
    if (value === "lowest price") {
      const lowestPriceGoods = data.sort((el1, el2) =>
        el1.price.localeCompare(el2.price, undefined, { numeric: true })
      );
      setProductsInfo([...lowestPriceGoods]);
    }
    if (value === "highest price") {
      const highestPriceGoods = data.sort((el1, el2) =>
        el2.price.localeCompare(el1.price, undefined, { numeric: true })
      );
      setProductsInfo([...highestPriceGoods]);
    }
    if (value === "all") {
      setProductsInfo(data);
    }
  };

  const searchProducts = (products) => {
    if (searchValue.toLowerCase().trim() === "") {
      setProductsInfo(products);
    } else {
      const seekedItem = productsInfo.filter(
        (product) =>
          product.name.toLowerCase().trim().includes(searchValue) ||
          product.category.toLowerCase().trim().includes(searchValue)
      );
      setProductsInfo(seekedItem);
    }
  };

  return (
    <div>
      <SearchInput
        handleChange={handleChange}
        searchValue={searchValue}
        selectedChangeFilter={selectedChangeFilter}
      />
      <Products
        data={data}
        searchValue={searchValue}
        productsInfo={productsInfo}
        searchProducts={searchProducts}
      />
    </div>
  );
};
export default App;

I tried this one below but doesn't work我在下面尝试了这个但不起作用

if (value === "all") {
const copiedData = [...data]
  setProductsInfo(copiedData);
}

This is because while sorting you are sorting on your original data array.这是因为在排序时,您正在对原始数据数组进行排序。 So the item ordering changes in it.所以其中的项目排序发生了变化。 You can copy your data into a seperate array and sort then as shown below.您可以将数据复制到单独的数组中,然后进行排序,如下所示。

Updated Codesandbox Link -https://codesandbox.io/s/fervent-napier-3rhvs4?file=/src/App.js更新了 Codesandbox 链接 -https://codesandbox.io/s/fervent-napier-3rhvs4?file=/src/App.js

if (value === "lowest price") {
      const productsToSort = [...data]
      const lowestPriceGoods = productsToSort.sort((el1, el2) =>
        el1.price.localeCompare(el2.price, undefined, { numeric: true })
      );
      setProductsInfo([...lowestPriceGoods]);
    }
    if (value === "highest price") {
      const productsToSort = [...data]
      const highestPriceGoods = productsToSort.sort((el1, el2) =>
        el2.price.localeCompare(el1.price, undefined, { numeric: true })
      );
      setProductsInfo([...highestPriceGoods]);
    }

I think it's because data.sort() change your javascript data object, and doesn't return a new array like filter.我认为这是因为 data.sort() 更改了您的 javascript 数据 object,并且不会返回像过滤器这样的新数组。

Try by replacing data.sort() by [...data].sort()尝试将 data.sort() 替换为 [...data].sort()

const selectedChangeFilter = (e) => {
    const { value } = e.target;
    if (value === "sporting goods") {
      const sportingGoods = data.filter(
        (product) => product.category === "Sporting Goods"
      );
      setProductsInfo(sportingGoods);
    }
    if (value === "electronics") {
      const electronicsGoods = data.filter(
        (product) => product.category === "Electronics"
      );
      setProductsInfo(electronicsGoods);
    }
    if (value === "lowest price") {
      const lowestPriceGoods = [...data].sort((el1, el2) =>
        el1.price.localeCompare(el2.price, undefined, { numeric: true })
      );
      setProductsInfo([...lowestPriceGoods]);
    }
    if (value === "highest price") {
      const highestPriceGoods = [...data].sort((el1, el2) =>
        el2.price.localeCompare(el1.price, undefined, { numeric: true })
      );
      setProductsInfo([...highestPriceGoods]);
    }
    if (value === "all") {
      setProductsInfo(data);
    }
  };

This is happening because Array.sort() method is mutable.这是因为 Array.sort() 方法是可变的。 You are sorting the data array and returning the sorted value.您正在对数据数组进行排序并返回排序后的值。 This is a short example of what is happening.这是正在发生的事情的一个简短示例。

const fruits = ["Melon", "Avocado", "Apple"];

console.log(fruits)  // ["Melon", "Avocado", "Apple"]

fruits.sort()

console.log(fruits)  // [ 'Apple', 'Avocado', 'Melon' ]

In order to avoid that in your code you can destructure the data array.为了避免在您的代码中出现这种情况,您可以解构数据数组。 This will create a new array pointing it to a different place in the memory.这将创建一个新数组,将其指向 memory 中的不同位置。

  const selectedChangeFilter = (e) => {
    const { value } = e.target;
    // { . . . }
    
    if (value === "lowest price") {
      const lowestPriceGoods = [...data].sort((el1, el2) =>
        el1.price.localeCompare(el2.price, undefined, { numeric: true })
      );
      setProductsInfo([...lowestPriceGoods]);
    }
    if (value === "highest price") {
      const highestPriceGoods = [...data].sort((el1, el2) =>
        el2.price.localeCompare(el1.price, undefined, { numeric: true })
      );
      setProductsInfo([...highestPriceGoods]);
    }

  //  { . . . }

}

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

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