当我在 Next.js 应用程序上使用钩子时,出现“错误:无效钩子调用”。我不知道为什么会收到此错误,因为我认为它是在函数组件内部调用的?
Server Error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
pages/index.js (16:44) @ getStaticProps
14 |
15 | export const getStaticProps = async () => {
> 16 | const { data, loading, error } = useQuery(LINGO_QUERY);
| ^
17 |
18 | return {
19 | props: {
在此处查看我的代码和框:https://codesandbox.io/s/empty-sea-hjunv
答案 0 :(得分:2)
你不能在 React 组件之外使用钩子。
然后,在 nextjs 中,import React, { useEffect, useState } from "react";
import { StyleSheet, View, FlatList, Text, Image } from "react-native";
import { Input, Button, ListItem, Avatar } from "react-native-elements";
import Icon from "react-native-vector-icons/FontAwesome";
import axios from "axios";
export default function App() {
const [searchQuery, setSearchQuery] = useState("");
const [data, setData] = useState([]);
const [mostrar, setMostrar] = useState(false);
useEffect(() => {
getLivro();
console.log("useEffect");
}, []);
function getLivro(searchQuery) {
if (searchQuery !== undefined) {
setMostrar(true);
}
axios
.get(`https://www.googleapis.com/books/v1/volumes?q=${searchQuery}`)
.then(function (response) {
setData(response.data.items[0].volumeInfo);
console.log(response.data.items[0].volumeInfo);
});
}
return (
<View style={styles.container}>
{mostrar ? (
<FlatList
data={data.title}
renderItem={({ item }) => (
<>
<Text>{data.title}</Text>
<Image
source={{
uri: data.imageLinks.thumbnail,
}}
style={{ width: 100, height: 100 }}
/>
</>
)}
keyExtractor={({ id }, index) => id}
/>
) : (
<></>
)}
<Input
placeholder="Busque pelo nome do livro ou autora ou editora"
onChangeText={(value) => {
setSearchQuery(value);
}}
onKeyPress={(value) => {
setSearchQuery(value);
}}
leftIcon={<Icon name="user" size={24} color="black" />}
/>
<Button
onPress={() => {
getLivro(searchQuery);
}}
icon={<Icon name="search" size={15} color="white" />}
/>
</View>
);
}
是在服务器端上下文中使用的函数,并在构建时进行预渲染。
答案 1 :(得分:0)
您不能在组件外部使用钩子。你的 getStaticProps
不是一个组件,它是一个你用来返回 props 的函数。
您可以在此处阅读更多相关信息:https://reactjs.org/warnings/invalid-hook-call-warning.html#breaking-the-rules-of-hooks
只需在组件中使用 useQuery
钩子并使用它来获取一些数据并定期呈现它。
您可能正在某处执行该函数作为常规函数。
要使用钩子,您需要在组件内部调用它,这是一个规则,因为钩子可能会返回一些 jsx,而 React 将其设为强制性。