反应打字稿和useCallback

时间:2020-05-28 09:22:00

标签: reactjs typescript react-hooks usecallback

我正在尝试使用Typescript和useCallback,但出现此错误

Expected 0 arguments, but got 1

这是我的代码

const searchFriends = useCallback(() => (filterValue: string): void => {
    if (dataState.length <= INITIAL_FRIENDS_API_REQUEST) fetchAllFriends()
    const filterValueInsensitive = filterValue.toLowerCase()
    const filtered = dataState.filter((friend: Friends) => {
      return friend.displayName?.toLowerCase().includes(filterValueInsensitive)
    }) 
    setFriendsDisplayState(filtered)
  }, [dataState,fetchAllFriends]) 

  const handleChangeSearchInput = (
    e: React.ChangeEvent<HTMLInputElement>
  ): void => searchFriends(e.currentTarget.value) // ERROR here "Expected 0 arguments, but got 1"

任何想法我该如何解决?

1 个答案:

答案 0 :(得分:3)

您正在使用useCallback之类的useMemo's语法。它不需要currying函数。正确的书写方式就像

const searchFriends = useCallback((filterValue: string): void => {
    if (dataState.length <= INITIAL_FRIENDS_API_REQUEST) fetchAllFriends()
    const filterValueInsensitive = filterValue.toLowerCase()
    const filtered = dataState.filter((friend: Friends) => {
      return friend.displayName?.toLowerCase().includes(filterValueInsensitive)
    }) 
    setFriendsDisplayState(filtered)
  }, [dataState,fetchAllFriends])