首页 > 解决方案 > useEffect,覆盖 if 语句

问题描述

我正在尝试通过使用对象值排序来对列表进行排序,但是使用useState时,if 语句仅在 if 语句中触发,但不会同时在ifand中触发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])

这也失败了。

有关更多信息,请查看此代码

标签: javascriptreactjsreact-hooks

解决方案


您说过国家/地区列表(间接)来自上下文。您不能像这样直接修改上下文项。如果您希望组件对该列表具有自己的排序顺序,则必须在每次渲染时对其进行排序(可能不理想)或将排序版本存储在状态中,并根据需要进行更新。

这些方面的东西:

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

推荐阅读