简体   繁体   English

使用 useState、React 时 Hook 调用无效

[英]Invalid Hook call when using useState, React

I have little issue I face the first time.我第一次遇到的小问题。 I'm trying to use a simple useState but for some reason I can't understand why React throws me back an error and whatever I'm trying to do-nothing fix it.我正在尝试使用一个简单的 useState 但由于某种原因我无法理解为什么 React 会抛出一个错误以及我正在尝试做的任何事情 - 什么都不修复它。

在此处输入图像描述

that's the image of the error: error description:那是错误的图像:错误描述:

Error: Invalid hook call.错误:无效的挂钩调用。 Hooks can only be called inside of the body of a function component.钩子只能在 function 组件的主体内部调用。 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这可能是由于以下原因之一: 1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能有多个 React 副本同一个应用

my code:(very simple)我的代码:(非常简单)

 import React, {useState} from "react"; function Login() { const [user, setUser] = useState({}); return <div> why error? </div>; } export default Login;

Tried following their solution with no luck of succeeding... thanks尝试按照他们的解决方案没有成功...谢谢

EDIT: this is where I render the component -编辑:这是我渲染组件的地方 -

 import React from "react"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import Home from "./components/Home"; import Contact from "./components/Contact"; import Login from "./components/Login"; import Register from "./components/Register"; import NotFound from "./components/NotFound"; import Navbar from "./components/Navbar"; function App() { return ( <Router> <div className="App"> <Navbar /> <Switch> <Route path="/" exact render={Home} /> <Route path="/contact" exact component={Contact} /> <Route path="/login" exact render={Login} /> <Route path="/register" exact render={Register} /> <Route render={NotFound} /> </Switch> </div> </Router> ); }...

The issue here is how you're rendering your component.这里的问题是你如何渲染你的组件。 You can't do:你不能这样做:

Login()

but you can do:但你可以这样做:

<Login />

Update: similarly, you can't do:更新:同样,你不能这样做:

<Route path="/login" exact render={Login} />

you need:你需要:

<Route path="/login" exact render={() => <Login />} />

The function itself has no errors. function 本身没有错误。 Tried this in another component in a different file.在另一个文件的另一个组件中尝试了这个。 Check for errors elsewhere.检查其他地方的错误。 What were the other 40 lines in the code?代码中的其他 40 行是什么?

And what's the version of React? React 的版本是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM