【发布时间】:2020-04-16 17:50:32
【问题描述】:
我的 React 项目中有一个容器组件,其中包含两个独立的组件。一个组件是位置列表,另一个是该列表的过滤部分。
过滤器部分向容器发送一个动作,容器根据条件对列表重新排序,并将最终的“过滤”列表传递回位置列表组件。
现在,排序依据过滤器是一个选择下拉菜单,其中选项值设置为字符串(如下所示),然后将其传递给容器。
<SelectDropdown value={sort} onChange={handleSortChange}>
<option value={''}>Select</option>
<option value={'alphaAsc'}>Alphabetical Asc</option>
<option value={'alphaDesc'}>Alphabetical Desc</option>
</SelectDropdown>
在容器内,我有一个简单的按字母顺序排序的函数,可以根据地址值按升序或降序对列表进行排序和呈现,这就是我的应用程序不断崩溃并抛出错误 TypeError: Cannot read property 'localeCompare' of undefined 的地方,但我并不完全确定为什么。
下面是我的原始函数以及我正在使用它的行。
Alphabetical Sort function
export const alphabeticalSort = property => {
let sortOrder = 1;
if (property[0] === '-') {
sortOrder = -1;
property = property.substr(1);
}
return function(a, b) {
if (sortOrder === -1) {
return b[property].localeCompare(a[property]);
} else {
return a[property].localeCompare(b[property]);
}
};
};
How I'm calling it
if (sort === 'alphaAsc') {
filteredLocations = filteredLocations.sort(alphabeticalSort(l => l.address.addressLine1)).slice();
}
Filtered Locations
const allLocations = store.get('locations');
let filteredLocations = allLocations.slice();
Location Structure
locations: [
{
name: 'Fictional Place',
address: {
addressLine1: '123 Imaginary Drive',
line2: '',
city: 'Philadelphia',
state: 'PA'
zip: '12345'
}
...
},
{
name: 'California Dreaming',
address: {
addressLine1: '456 Somewhere Blvd',
line2: '',
city: 'Sacramento',
state: 'CA'
zip: '67890'
}
...
},
....
【问题讨论】:
-
在您的问题中添加
filteredLocations -
刚刚添加了过滤的位置和位置结构是什么样的
-
你能从下面的答案中得到帮助吗?
-
嘿,不幸的是没有,它现在抛出一个新错误,说
TypeError: Cannot read property '0' of undefined -
知道了,谢谢!
标签: javascript reactjs typescript