在useEffect挂钩中使用外部函数未定义

时间:2020-10-28 08:16:44

标签: reactjs next.js

useEffect钩子中的

我使用了一个函数来向api发送请求以进行搜索。 函数名称是searchCharacters,它在组件外部。 我得到错误 TypeError: searchCharacters(...) is undefined当时我的代码受到谴责。为什么?如何解决这个问题?

错误img: enter image description here

function Dashboard() {

const [searchParam, setSearchParam] = useState("");
const [results, setResults] = useState([]);
const [isSearching, setIsSearching] = useState(false)
const debouncedSearchTerm = useDebounce(searchParam, 500);

useEffect(  ()=> {
        if(debouncedSearchTerm){

            setIsSearching(true);
            searchCharacters(debouncedSearchTerm).then(res => {
                setIsSearching(false);
                console.log("im search result", res);
                setResults(res);
            });

        }else{

            setResults([]);

        }
    }, [debouncedSearchTerm]);
}

function searchCharacters(search){
    api.get(`client/search?q=${search}`).then(
        (res) => {
            return res.data;
        }
    ).catch( e => {
        console.log(e);
        return [];
    })
}

export default Dashboard;

1 个答案:

答案 0 :(得分:2)

searchCharacters不会返回Promise的链接。从api.get返回searchCharacters Promise链。

function searchCharacters(search) {
  return api
    .get(`client/search?q=${search}`)
    .then((res) => {
      return res.data;
    })
    .catch((e) => {
      console.log(e);
      return [];
    });
}

或更简洁

const searchCharacters = (search) =>
  api
    .get(`client/search?q=${search}`)
    .then((res) => res.data)
    .catch((e) => {
      console.log(e);
      return [];
    });