javascript - useEffect,覆盖 if 语句
问题描述
我正在尝试通过使用对象值排序来对列表进行排序,但是使用useState
时,if 语句仅在 if 语句中触发,但不会同时在if
and中触发else
:
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])
这也失败了。
有关更多信息,请查看此代码
解决方案
您说过国家/地区列表(间接)来自上下文。您不能像这样直接修改上下文项。如果您希望组件对该列表具有自己的排序顺序,则必须在每次渲染时对其进行排序(可能不理想)或将排序版本存储在状态中,并根据需要进行更新。
这些方面的东西:
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
推荐阅读
- ajax - 如何在html头中写入token以及如何使用?
- clojure - Clojure 读取字符串
- ios - IOS 我可以在应用内购买中获取有关谁购买了我的产品的用户信息吗?
- php - 将路径的基本名称注入 find exec 命令
- sql-server - nodejs mssql 只调用一次
- php - 如何让 WordPress 基于 slug 创建查询?
- android - 在包“android”中找不到属性“appComponentFactory”的资源标识符
- json - Elasticsearch / Kibana错误:超出范围
- angular - 如何从`router-outlet`调用兄弟组件方法?
- sql - 检查多个项目的存在