useEffect
钩子中的我使用了一个函数来向api发送请求以进行搜索。
函数名称是searchCharacters
,它在组件外部。
我得到错误
TypeError: searchCharacters(...) is undefined
当时我的代码受到谴责。为什么?如何解决这个问题?
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;
答案 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 [];
});