反应挂钩打字稿如何更新状态

时间:2021-05-14 17:18:34

标签: javascript reactjs typescript react-hooks

嗨,朋友们,我在从 api 获取数据后无法更新状态。谁能帮我弄清楚。顺便说一句,我是打字稿的新手。

type FrequentlySearches = {
    value: string;
    count: string;
};

const initialFrequentlySearch: FrequentlySearches[] = [{
    value: '',
    count: '',
}];

export const GetFrequentlySearches = () => {

    const [data, dataSet] = useState(initialFrequentlySearch);

    const fetchFrequentlySearches = useCallback(async () => {
        let response = await fetch(url_pathname)
        let datas = await response.json()
        for (const key in datas) {
            // how  to update the state here !!!
            dataSet({
                value: datas[key].value,
                count: datas[key].count
            })
        }

    }, [url_pathname])


    useEffect(() => {
        fetchFrequentlySearches()
    }, [url_pathname])

};

1 个答案:

答案 0 :(得分:0)

你需要

(1) 正确输入 fetch,参见 here

(2) data 是一个对象数组,所以

        dataSet({
            value: datas[key].value,
            count: datas[key].count
        })

没有多大意义 - 而是将一个对象数组传递给状态设置器函数。

将响应的对象值作为数组可能会更容易 - 无需手动迭代。

useCallback 也是完全多余的。

export const GetFrequentlySearches = () => {
    const [data, setData] = useState(initialFrequentlySearch);
    useEffect(() => {
        fetch(url_pathname)
        .then((response => response.json()))
        .then((datasUntyped) => {
            const datas = datasUntyped as FrequentlySearches[];
            setData(Object.values(datas));
        })
        // .catch(handleErrors);
    }, [url_pathname])

}

如果API结果是一个对象数组而不是一个对象的对象,那么你根本不需要Object.values,直接做

setData(datas);

如果 API 结果包含其他需要排除的对象属性,请先映射数组以将其删除:

setData(
  Object.values(datas)
    .map(obj => ({ value: obj.value, count: obj.count }))
);