流-无法调用“ data.map”,因为“ FetchData”中缺少属性“ map” [1]

时间:2019-05-15 19:05:16

标签: javascript reactjs flowtype

您好,我正在尝试通过自定义useFetch钩子使用flow。这是代码:

import React, { useState, useEffect } from 'react'

function useFetch<FetchData>(
  promiseFn: () => Promise<FetchData>,
  args?: any[]
) {
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState<?FetchData>()
  const [error, setError] = useState<?Error>()

  useEffect(() => {
    setLoading(true)

    promiseFn()
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false))
  })

  return {
    loading,
    data,
    error
  }
}
  
function fetchKeys() {
   return Promise.resolve([{ name: 'myKey' }])
}  
  
type KeysData = {
  name: string
}[]  
  
function MyKeysPage() {
	const { data, loading, error } = useFetch<KeysData>(fetchKeys)
    
    if(!data) return 'Loading...'

    return data.map(key => (<div>{key.name}</div>))
}

但是它抛出一个错误:

  

无法调用data.map,因为map [1]中缺少属性FetchData

您可以在此处进行更好的查看:

https://flow.org/try/#0JYWwDg9gTgLgBAJQKYEMDGMA0cDecCuAzkgMowoxLZFICiAZvUhnAL5z1QQhwDkUqDLwBQw+vgB2GYBAkFiAMSQw0ACwA8SlaoAiFFAD4AFMLhwwXEMEUSAXHCMBKOAF4DcAAqXrSTcrV65AaYpnAoUADmhAD89igSAJ4A2gC6ws44oWiyhPBJADYQKAAmwBIR2MQwADJFpeUprvKk5JRG9Cj5xI5ZOXnF+pXKgSiNLs1kFL7RWgH6xj1m2RK5cElIUFxQQzC0m9BjE63Te1sLomY0DEwYRk6u7plmZlW1JWURRjBQ+Eg9oWYLNwfAoJE4Ac8AHQwVRIMFVEaLZ5mSFoChqIxVU7QJHIyH0MqdfIJO7ONxwV51D7tTrdJGsf5mAQwfBQORPZ6Fd7lELIgbkXnPDZbUKsYRisxiSTSWQcfyqADSSAShHuHLgzNZci8wOIkIEhAg+QAbkgjEk8BIUCAkPZeCAEkqErw2Ckeuw4KFhDAEmAkHAnYQRk0OVabfZclAPuLUpLJeIpDAZHIALKO5WEDwoCJmjLCACQy1WeH5KGwXPqFTgwugbCaNFmGkDI2MTG0gdxnuRwHoRgAhKXnJq2Xw3pXIRORBDh3JS5CQCgwEYANbKh4OdSlY0GHCrhKQsNIVjqAD0W4MjndQA

所以我不知道该如何解决。感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

看来Flow不能正确推断返回类型。显式输入useFetch有助于:

function useFetch<FetchData>(
  promiseFn: () => Promise<FetchData>,
  args?: any[]
): {data: ?FetchData, loading: bool, error: ?Error} {
  // ...
}

Playground link