如何调用在打字稿中使用钩子的函数?

时间:2019-05-26 19:02:29

标签: reactjs typescript

我正在尝试向我的react项目添加typescript(当然是im的)。我写了一个从我写的api中获取数据的钩子。我想添加类型但打字稿无法编译,因为渲染开始时状态未定义。我正在猜测。问题是在VictoryPie组件中调用formatData函数。我得到的错误是:

TypeScript error: Argument of type 'boolean | never[]' is not assignable to parameter of type 'Data[]'.
  Type 'false' is not assignable to type 'Data[]'.  TS2345

    26 |         <VictoryPie
    27 |           colorScale={['tomato', 'orange', 'gold', 'cyan', 'navy']}
  > 28 |           data={formatData(graphData)}
       |                            ^
    29 |           x="description"
    30 |           y="amount"
    31 |         />
import React from 'react';
import {useFetch} from '../hooks';
import {VictoryPie} from 'victory';

interface Data {
  _id: number,
  id: string,
  userName: string,
  amount: number,
  description: string,
  time: string,
}

const Graph = () => {
  const [graphData, loading] = useFetch('/api/Kamil');
  const formatData = (inputData: Array<Data>) => {
    return inputData.map(
      ({_id, id, time, userName, ...keepAttrs}) => keepAttrs,
    );
  };
  return (
    <>
      {loading ? (
        'Loading...'
      ) : (
        <VictoryPie
          colorScale={['tomato', 'orange', 'gold', 'cyan', 'navy']}
          data={formatData(graphData)}
          x="description"
          y="amount"
        />
      )}
    </>
  );
};
export default Graph;

挂钩

import {useState, useEffect} from 'react';
import axios from 'axios';

function useFetch(url: string) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  async function fetchUrl() {
    const response = await axios(url);
    console.log(response);
    setData(response.data)
    setLoading(false);
  }
  useEffect(() => {
    fetchUrl();
  }, []);
  return [data, loading];
}
export { useFetch };

1 个答案:

答案 0 :(得分:1)

这里有2个问题。

您需要声明您的钩子返回元组。现在,打字稿假定您要返回数据数组并以任何顺序加载。

此外,您还需要声明希望将哪种结果作为获取结果。

您的钩子应该看起来像

function useFetch<ExpectedResult>(url: string, initialData: ExpectedResult): [ExpectedResult, boolean] {
  const [data, setData] = useState(initialData);
  const [loading, setLoading] = useState(true);

  async function fetchUrl() {
    const response = await axios(url);
    console.log(response);
    setData(response.data)
    setLoading(false);
  }
  useEffect(() => {
    fetchUrl();
  }, [url]); // <<-- when url is changed you propably want to re-fetch
  return [data, loading];
}

然后使用时

这样做

type DataFromServer = Date[];

const [data, isLoading] = useFetch<DataFromServer>('/api/Kamil', []);

现在打字稿知道[data, isLoading]应该是什么。