javascript 如何解决React中的Invalid Hook调用错误,当尝试使用路由/导航时

p5fdfcr1  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(174)

我目前正在处理一个项目,并不断得到这个错误与我的路由:

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.
    at Object.throwInvalidHookError (react-dom.development.js:16227:1)
    at Object.useContext (react.development.js:1618:1)
    at useInRouterContext (hooks.tsx:85:1)
    at Navigate (components.tsx:196:1)
    at Login.jsx:24:1

这是我编写的应用程序的组件:

import React, { useState } from "react";
import { useLocation } from "react-router-dom";
import { Navigate } from "react-router-dom";

const Login = () => {
  const location = useLocation();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  const submitForm = (event) => {
    event.preventDefault();
    fetch("http://localhost:8000/users")
      .then((response) => response.json())
      .then((data) => {
        const user = data.find(
          (user) =>
            user.email &&
            user.email.toLowerCase() === email.toLowerCase() &&
            user.password &&
            user.password.toLowerCase() === password.toLowerCase()
        );
        if (user) {
          Navigate("/profile");
        } else {
          setErrorMessage("Invalid email or password");
        }
      })
      .catch((error) => console.log(error));
  };

  return (
    <div>
      <form onSubmit={submitForm}>
        <div>
          <label htmlFor="email">Enter Email Address:</label>
          <input
            type="text"
            name="email"
            id="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>
        <div>
          <label htmlFor="password">Enter Password:</label>
          <input
            type="password"
            name="password"
            id="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>
        <button type="submit">Login</button>
      </form>
      {errorMessage && <p>{errorMessage}</p>}
    </div>
  );
};

export default Login;
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Profile from "./components/Profile";
import Login from "./components/Login";

function App() {
  return (
    <div className="wrapper">
      <h1>Application</h1>
      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/profile" element={<Profile />} />
        </Routes>
      </Router>
    </div>
  );
}

export default App;
import React from "react";

const Profile = () => {
  return (
    <div>
      <h2>Dashboard</h2>
      <p>Welcome to your profile page!</p>
      {/* Display user profile information here */}
    </div>
  );
};

export default Profile;

我已经尝试了几个修复,例如重新安装VSCode/Node.js,启动一个新的React应用程序,使用npm链接../myapp/node_modules/react......我在过去24小时内找到的大多数修复。
以下是我目前的react版本:

PS C:\Users\Admin\Documents\SD Semester2\Final_Sprint\finalsprint> npm ls react
finalsprint@0.1.0 C:\Users\Admin\Documents\SD Semester2\Final_Sprint\finalsprint
├─┬ @testing-library/react@13.4.0
├─┬ react-dom@18.2.0
│ └── react@18.2.0 deduped
├─┬ react-router-dom@6.10.0
│ └── react@18.2.0 deduped
├─┬ react-router@6.10.0
│ └── react@18.2.0 deduped
├─┬ react-scripts@5.0.1
│ └── react@18.2.0 deduped
└── react@18.2.0

此外,当我尝试在浏览器控制台上使用React.version查看react版本时,它说React未定义。

roejwanj

roejwanj1#

不要在代码中直接使用Navigate,而应使用

const navigate = useNavigate()

这是你的登录文件代码

import React, { useState } from "react"; 
import { useLocation } from "react-router-dom";
 import { Navigate } from "react-router-dom";
    
    const Login = () => {  
 const location = useLocation();   
const [email, setEmail] = useState("");
   const [password, setPassword] = useState(""); 
  const [errorMessage, setErrorMessage] = useState("");
const navigate= useNavigate();
    
      const submitForm = (event) => {
        event.preventDefault();
        fetch("http://localhost:8000/users")
          .then((response) => response.json())
          .then((data) => {
            const user = data.find(
              (user) =>
                user.email &&
                user.email.toLowerCase() === email.toLowerCase() &&
                user.password &&
                user.password.toLowerCase() === password.toLowerCase()
            );
            if (user) {
              navigate("/profile");
            } else {
              setErrorMessage("Invalid email or password");
            }
          })
          .catch((error) => console.log(error));   };
    
      return (
        <div>
          <form onSubmit={submitForm}>
            <div>
              <label htmlFor="email">Enter Email Address:</label>
              <input
                type="text"
                name="email"
                id="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </div>
            <div>
              <label htmlFor="password">Enter Password:</label>
              <input
                type="password"
                name="password"
                id="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </div>
            <button type="submit">Login</button>
          </form>
          {errorMessage && <p>{errorMessage}</p>}
        </div>   ); };
    
    export default Login;

相关问题