[英]invalid hook call on data retrieved by axios
I'm trying to retrieve the JSON data from here and then update the state in a functional component.我正在尝试从此处检索 JSON 数据,然后在功能组件中更新 state。 Even though the code seems fine I'm getting an error saying its an invalid hook call.
尽管代码看起来不错,但我收到一个错误,说它是一个无效的钩子调用。
On the react documentation it said that I might have 2 different react apps in the same folder however I checked it with the command they gave and there was only 1. However I am running this from a django server and there is a different react app in a different django app (so in a completely different folder).在反应文档中,它说我可能在同一个文件夹中有 2 个不同的反应应用程序,但是我用他们给出的命令检查了它,只有 1 个。但是我从 django 服务器运行它,并且有一个不同的反应应用程序一个不同的 django 应用程序(所以在一个完全不同的文件夹中)。
const App = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
let url = "https://jsonplaceholder.typicode.com/posts";
axios.get(url).then(res => {
console.log(res.data);
// The code crashes here saying that it is an invalid hook call
useState(res.data);
}).catch(err => console.log(err));
}, []);
return (
<div>
This is just a place holder.
</div>
);
}
I have a feeling this might have something to do with the other react application in the django project but if anyone can see something that I can't I would appreciate the help.我觉得这可能与 django 项目中的其他反应应用程序有关,但如果有人能看到我看不到的东西,我将不胜感激。
Edit I realised that I was trying to call useState() in the useEffect hook when I should have been using the setPosts function that was already defined in the function.编辑我意识到当我应该使用已经在 function 中定义的 setPosts function 时,我试图在 useEffect 挂钩中调用 useState()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.