我试图通过使用对象值排序来对列表进行排序,但是使用 useState
时,if 语句仅在 if 语句中触发,而不是同时在 if
和 其他
:
const { countryList } = useCustomerData();
useEffect(()=>{
if(type === 'nationality'){
countryList.sort((a: CountryObject, b: CountryObject) =>
a.nationality.localeCompare(b.nationality))
}else {
countryList.sort((a: CountryObject, b: CountryObject) =>
a.country.localeCompare(b.country))
}
}, [countryList, type])
这是国家/地区列表:
[{country: 'Afghanistan', code: 'AF', prefix: '93', nationality: 'Afghan'}
1: {country: 'Ägypten', code: 'EG', prefix: '20', nationality: 'Egyptian'}
2: {country: 'Åland-Inseln', code: 'AX', prefix: '+358-18', nationality: 'Åland-Inseln'}
3: {country: 'Albanien', code: 'AL', prefix: '355', nationality: 'Albanisch'}
4: {country: 'Algerien', code: 'DZ', prefix: '213', nationality: 'Algerian'}]
列表很长,但这只是示例列表。
我的第二次尝试:
const [countryFinal, setCountryFinal] = useState<CountryType[]>([])
const value = useMemo(() => _get(values, name), [values, name]);
useEffect(()=>{
if(type === 'nationality'){
setCountryFinal(countryList.sort((a: CountryObject, b: CountryObject) =>
a.nationality.localeCompare(b.nationality)))
}else {
setCountryFinal(countryList.sort((a: CountryObject, b: CountryObject) =>
a.country.localeCompare(b.country)))
}
}, [countryList, type, setCountryFinal])
这也失败了。
有关更多信息,请查看此 code
最佳答案
您说过国家/地区列表(间接)来自上下文。您不能像这样直接修改上下文项。如果您希望组件对该列表有自己的排序顺序,则必须在每次渲染时对其进行排序(可能不理想)或在状态中存储排序版本,并根据需要进行更新。
大致如下:
const { countryList } = useCustomerData();
const [ sortedCountryList, setSortedCountryList ] = useState<CountryObject[]>([]); // (Or you could init it with `countryList`)
useEffect(()=>{
if (type === "nationality"){
setSortedCountryList(countryList.slice().sort((a: CountryObject, b: CountryObject) =>
a.nationality.localeCompare(b.nationality)
));
} else {
setSortedCountryList(countryList.slice().sort((a: CountryObject, b: CountryObject) =>
a.country.localeCompare(b.country)
));
}
}, [countryList, type]); // <=== Update the sorted list when either the context
// value or the sort type changes
// ...use `sortedCountryList` for rendering
关于javascript - useEffect,覆盖if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69223503/