React使用useState进行数组排序时出现“Cannot read properties of undefined (reading 'price')”错误的问题咨询
Hey there! Let's break down why you're running into this error and how to fix it.
What's causing the issue?
The key problem here is that Array.sort() modifies the original array in place. When you don't use useState, your component probably only renders once—so sorting the imported productData directly doesn't cause problems. But when you use useState, selecting a new sort option triggers a component re-render, and you end up calling productData.sort(type) again on the already modified original array. Over multiple re-renders, this messes up the original dataset, leading to cases where the sorting function tries to access price on an undefined element.
How to fix it
Here are the steps to resolve this:
Always sort a copy of the original array: Never modify the imported
productDatadirectly. Use the spread syntax to create a fresh copy before sorting:let productsPrice = [...productData].sort(type);This way, you're working with a duplicate of the original data every time, leaving the source array untouched and preventing data corruption across re-renders.
Optimize sorting with
useMemo(recommended): Right now, your sorting runs on every component render. Wrapping the sorted array inuseMemowill only re-run the sort when thetypestate changes, which improves performance. Update your code like this:import { useState, useMemo } from 'react'; // Inside your ProductsList component const sortedProducts = useMemo(() => { return [...productData].sort(type); }, [type, productData]); const products = sortedProducts.map((item) => { return <Product item={item} key={item.id} />; });Fix the sort direction checkboxes (bonus tip): Your current setup uses two independent checkboxes for ascending/descending, which allows users to check both at once (creating conflicting logic). Consider switching to radio buttons or a single select dropdown for direction. You could add another
useStateto track direction, then adjust your compare functions like this:const [direction, setDirection] = useState('asc'); // Modify your compare functions to respect direction const compareAscendingPrice = (a, b) => direction === 'asc' ? a.price - b.price : b.price - a.price;
With these changes, your original dataset stays intact, and each sort operation uses a clean copy—so you won't run into that "undefined" error when accessing properties like price anymore.
备注:内容来源于stack exchange,提问作者MouB25

