javascript - useEffect,覆盖if语句

标签 javascript reactjs react-hooks

我试图通过使用对象值排序来对列表进行排序,但是使用 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/

相关文章:

javascript - 使用左、右、下、上、主页和结束虚拟按钮的 HTML Texeare 插入符号控件

javascript - javascript if 的多个操作

javascript - .toFixed 函数不适用于 js-object

reactjs - React useEffect 在其依赖数组中有一个 spread 元素

javascript - useState hook 的 set State 函数无法与 socket.io 一起正常工作

javascript - 在 useEffect 中 react 永无止境的循环

javascript - 如何随机打乱包含名称字符串的数组?

javascript - 自动填写 react 不起作用

javascript - 在 useEffect 中使用 componentDidUpdate 代码以及 DidMount 和 UnMount

javascript - 如何在单元测试环境中模拟 browserHistory?