简体   繁体   English

React-router 显示无效的钩子调用

[英]React-router showing invalid hook call

An invalid hook error occurred in my react app caused by react-router but I can't seem to detect where it's coming from.由 react-router 引起的我的反应应用程序中发生了一个无效的钩子错误,但我似乎无法检测到它来自哪里。 The full error reads as follows:完整的错误如下:

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.

I don't have a mismatch of React versions nor is the error caused (can't say for sure but I don't) by any of the reasons stated.我没有 React 版本不匹配,也不是由上述任何原因引起的错误(不能肯定,但我没有)。 I followed the react-router docs here .我在这里关注了 react-router 文档。 I know I'm messing up something but I don't know where.我知道我搞砸了,但我不知道在哪里。

Below are the necessary components, starting from the entry file.以下是必要的组件,从入口文件开始。

index.js index.js

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import {
  ApolloProvider,
  ApolloClient,
  createHttpLink,
  InMemoryCache,
} from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import {AUTH_TOKEN} from "./constants";
import App from "./components/App";
import "./styles/index.css";

const httpLink = createHttpLink({ uri: "http://localhost:4000" });

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem(AUTH_TOKEN);

  return {
    ...headers,
    authorization: token ? `Bearer ${token}` : "",
  };
});

/*Instantiates Apollo client and connect to GraphQL server.
This will take the server link and an instantiation of the cache funtionality*/
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

ReactDOM.render(
  <BrowserRouter>
    <ApolloProvider client={client}>
      <React.StrictMode>
        <App />
      </React.StrictMode>
    </ApolloProvider>
  </BrowserRouter>,
  document.getElementById("root")
);

App.js应用程序.js

import React from "react";
import LinkList from "./LinkList";
import CreateLink from "./CreateLink";
import Header from "./Header";
import Login from './Login';
import { Routes, Route } from "react-router-dom";
import "../styles/App.css";

function App() {
  return (
    <div className="center w85">
      <Header />
      <div className="ph3 pv1 background-gray">
        <Routes>
          <Route path="/" element={<LinkList/>} />
          <Route path="/create" element={<CreateLink/>} />
          <Route path="/login" element={<Login/>} />
        </Routes>
      </div>
    </div>
  );
}

export default App;

Header.js Header.js

import React from "react";
import { useNavigate, Link } from "react-router-dom";
import { AUTH_TOKEN } from "../constants";

export default function Header() {
    const history = useNavigate();
    const authToken = localStorage.getItem(AUTH_TOKEN);

    return (
        <div className="flex pa1 justify-between nowrap orange">
            <div className="flex flex-fixed black">
                <div className="fw7 mr1">Hacker News</div>
                <Link to="/" className="ml1 no-underline black">
                    new
                </Link>
                <div className="ml1">|</div>
                <Link to="/top" className="ml1 no-underline black">
                    top
                </Link>
                <div className="ml1">|</div>
                <Link to="/search" className="ml1 no-underline black">
                    search
                </Link>
                {authToken && (
                    <div className="flex">
                        <div className="ml1">|</div>
                        <Link to="/create" className="ml1 no-underline black">
                            submit
                        </Link>
                    </div>
                )}
            </div>
            <div className="flex flex-fixed">
                {authToken ? (
                    <div
                        className="ml1 pointer black"
                        onClick={() => {
                            localStorage.removeItem(AUTH_TOKEN);
                            history.push(`/`);
                        }}
                    >
                        logout
                    </div>
                ) : (
                    <Link to="/login" className="ml1 no-underline black">
                        login
                    </Link>
                )}
            </div>
        </div>
    );
}

LinkList.js链接列表.js

import React from "react";
import { useQuery, gql } from "@apollo/client";
import Link from "./Link";

const LinkList = () => {

  const FEED_QUERY = gql`
    {
      feed {
        id
        links {
          id
          createdAt
          url
          description
        }
      }
    }
  `;

  const { loading, error, data } = useQuery(FEED_QUERY);

  if (loading) return <p style={{padding: 20, textAlign:"center"}}>Loading...</p>;

  if (error) console.log(error);

  return (
    <div>
      {data &&
        data.feed.links.map((link) => <Link key={link.id} link={link} />)}
    </div>
  );
};

export default LinkList;

CreateLink.js创建链接.js

import React, { useState } from "react";
import { useMutation, gql } from "@apollo/client";
import { useNavigate } from "react-router-dom";

export default function CreateLink() {
    const [formState, setFormState] = useState({ description: "", url: "" });

    const history = useNavigate();

    const CREATE_LINK_MUTATION = gql`
        mutation PostMutation($url: String!, $description: String!) {
            post(url: $url, description: $description) {
                id
                createdAt
                url
                description
            }
        }
    `;

    const [createLink] = useMutation(CREATE_LINK_MUTATION, {
        variables: {
            description: formState.description,
            url: formState.url,
        },
        onCompleted: () => history.push("/")
    });

    return (
        <div>
            <form
                onSubmit={(e) => {
                    e.preventDefault();
                    createLink();
                }}
            >
                <div className="flex flex-column mt3">
                    <input
                        type="text"
                        className="mt2"
                        placeholder="A description for the link"
                        onChange={(e) =>
                            setFormState({
                                ...formState,
                                description: e.target.value,
                            })
                        }
                        value={formState.description}
                    />
                    <input
                        className="mb2"
                        value={formState.url}
                        onChange={(e) =>
                            setFormState({
                                ...formState,
                                url: e.target.value,
                            })
                        }
                        type="text"
                        placeholder="The URL for the link"
                    />
                </div>
                <button type="submit">Submit</button>
            </form>
        </div>
    );
}

Login.js登录.js

import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { gql, useMutation } from "@apollo/client";
import { AUTH_TOKEN } from '../constants';

export default function Login() {
    let history = useNavigate();

    const [formState, setFormState] = useState({
        login: true,
        email: "",
        password: "",
        name: "",
    });

    const SIGNUP_MUTATION = gql`
        mutation SignupMutation(
            $email: string
            $password: string
            $name: string
        ) {
            signup(email: $email, password: $password, name: $name) {
                token
                user {
                    name
                    email
                }
            }
        }
    `;

    const [signup] = useMutation(SIGNUP_MUTATION, {
        variables: {
            email: formState.email,
            password: formState.password,
            name: formState.password,
        },
        onCompleted: ({ signup }) => {
            localStorage.setItem(AUTH_TOKEN, signup.token);
            history.push("/create");
        },
    });

    const LOGIN_MUTATION = gql`
        mutation LoginMutation($email: string, $password: string) {
            login(email: $email, password: $password) {
                token
            }
        }
    `;

    const [login] = useMutation(LOGIN_MUTATION, {
        variables: {
            email: formState.email,
            password: formState.password,
        },
        onCompleted: ({ login }) => {
            localStorage.setItem(AUTH_TOKEN, signup.token);
            history.push("/");
        },
    });

    return (
        <div>
            <h4 className="mv3">{formState.login ? "Login" : "Sign Up"}</h4>
            <div className="flex flex-column">
                {!formState.login && (
                    <input
                        value={formState.name}
                        onChange={(e) =>
                            setFormState({
                                ...formState,
                                name: e.target.value,
                            })
                        }
                        type="text"
                        placeholder="Your name"
                    />
                )}
                <input
                    value={formState.email}
                    onChange={(e) =>
                        setFormState({
                            ...formState,
                            email: e.target.value,
                        })
                    }
                    type="text"
                    placeholder="Your email address"
                />
                <input
                    value={formState.password}
                    onChange={(e) =>
                        setFormState({
                            ...formState,
                            password: e.target.value,
                        })
                    }
                    type="password"
                    placeholder="Choose a safe password"
                />
            </div>
            <div className="flex mt3">
                <button
                    className="pointer mr2 button"
                    onClick={() => (formState.login ? login : signup)}
                >
                    {formState.login ? "login" : "create account"}
                </button>
                <button
                    className="pointer button"
                    onClick={(e) =>
                        setFormState({
                            ...formState,
                            login: !formState.login,
                        })
                    }
                >
                    {formState.login
                        ? "need to create an account?"
                        : "already have an account?"}
                </button>
            </div>
        </div>
    );
}

Installed version of React according to packages in project:根据项目中的包安装的 React 版本:

react-apollo-integration@0.1.0 c:\projects\react-apollo-integration\frontend
+-- @apollo/client@3.4.17
| `-- react@17.0.2 deduped
+-- @testing-library/react@11.2.7
| +-- react-dom@17.0.2 deduped
| `-- react@17.0.2 deduped
+-- react-dom@17.0.2
| `-- react@17.0.2 deduped
+-- react-scripts@4.0.3
| `-- react@17.0.2 deduped
`-- react@17.0.2

It looks like you are missing the router and a switch.看起来您缺少路由器和交换机。

 import React from "react"; import LinkList from "./LinkList"; import CreateLink from "./CreateLink"; import Header from "./Header"; import Login from './Login'; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import "../styles/App.css"; function App() { return ( <div className="center w85"> <Header /> <div className="ph3 pv1 background-gray"> <Router> <Switch> <Route path="/" element={<LinkList/>} /> <Route path="/create" element={<CreateLink/>} /> <Route path="/login" element={<Login/>} /> </Switch> </Router> </div> </div> ); } export default App;

I found out what I did wrong.我发现我做错了什么。 I installed the react-router package outside the project's directory.我在项目目录之外安装了react-router package。 My bad!我的错!

I deleted the npm modules and the Json file but it keeps installing back whenever I install react-router-dom which makes keep saying invalid hook...我删除了 npm 模块和 Json 文件,但是每当我安装 react-router-dom 时它都会重新安装,这使得一直说无效挂钩...

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

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