我正在编写一段代码,在 https://themoviedb.org
中搜索电影的详细信息代码是在 React 17.0.2 中使用 yarn、visual studio 代码编写的。
我正在从 useEffect 调用一个函数,该函数将从调用 TheMovieDB 的结果生成一个 json 文件
我收到以下错误,你能帮我吗? **错误:无效的钩子调用。钩子只能在函数组件的主体内部调用。 **
提前感谢您在此问题上投入的时间
useEffect(() => {
if (slideRows.length > 0 && searchTerm.length > 2) {
const searchResult = searchInTheMovieDB(category, searchTerm);
if (searchResult.results.length > 0) {
setSlideRows(searchResult);
} else {
setSlideRows(slides[category]);
}
} else {
setSlideRows(slides[category]);
console.log("slideRows", slideRows);
setSlideRows(slides[category]);
}, [category, searchTerm, slideRows, slides, theMovieDBApikey]);
}
export function searchInTheMovieDB(media_type, query) {
let result = {};
if (media_type === "tv") {
result = {
tv: [
{
title: `${media_type} search result`,
data: GetSearch(media_type, query),
},
],
};
} else {
result = {
movie: [
{
title: `${media_type} search result`,
data: GetSearch(media_type, query),
},
],
};
}
return result;
}
export function GetSearch(media_type, query) {
const [content, setContent] = useState([]);
useEffect(() => {
console.log("GetSearch", `${endpoint.Search}/${media_type}?query=${query}`);
api
.get(`${endpoint.Search}/${media_type}`, {
params: {
api_key,
query,
},
})
.then((res) => {
setContent(res.data.results);
})
.catch((error) => {
console.error("error.message", error.message);
});
}, [media_type, query]);
return { [media_type]: content };
}
答案 0 :(得分:0)
我增加了 useEffects 的数量来识别进程:
PS:我创建了一个 async 函数来从网络服务中获取数据
const [searchResults, setSearchResults] = useState([]);
import axios from "axios";
const api = axios.create({ baseURL: BASE_URL });
async function getSearch(media_type, query) {
api
.get(`${endpoint.Search}/${media_type}`, {
params: {
api_key,
query,
},
})
.then((res) => {
setSearchResults(res.data.results);
})
.catch((error) => {
console.error("error.message", error.message);
});
}
useEffect(() => {
if (searchResults.length > 0) {
setSlideRows({
tv: [
{
title: `${category} search result`,
data: searchResults,
},
],
});
}
}, [category, searchResults]);
useEffect(() => {
if (slideRows.length > 0 && searchTerm.length > 2) {
getSearch(category, searchTerm);
} else {
setSlideRows(slides[category]);
}
}, [searchTerm, slides]);
useEffect(() => {
if (searchResults.length > 0 && searchResults.results?.length > 0) {
setSlideRows(searchResults);
} else {
setSlideRows(slides[category]);
}
setSlideRows(slides[category]);
}, [searchResults]);