简体   繁体   English

为什么我不能从这个功能组件调用 React 钩子?

[英]Why can't I call a React hook from this functional component?

I'm trying to implement a navigation bar with the logout option.我正在尝试使用注销选项实现导航栏。

Here's the code for my functional component:这是我的功能组件的代码:

import React, { useState } from 'react';
import { Nav, NavDropdown } from 'react-bootstrap';
import { useSelector, useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';

function MainMenu(props) {
    const user = useSelector(state => state.user);
    const dispatch = useDispatch();
    const navigate = useNavigate();
    
    const handleLogout = () => {
        dispatch({
            type: 'user/logout'            
        });
        navigate('/home');
    };

    const logedInMenu = (<NavDropdown title={user.name} id="basic-nav-dropdown">
        <NavDropdown.Item href="/dashboard">Dashboard</NavDropdown.Item>
        <NavDropdown.Item href="/upload">Upload new Meme</NavDropdown.Item>
        <NavDropdown.Divider />
        <NavDropdown.Item href="#" onClick={handleLogout}>Logout</NavDropdown.Item>
    </NavDropdown>);

    const publicMenu = (<Nav className='me-auto'>
        <Nav.Link href="/login">Login</Nav.Link>
        <Nav.Link href="/signup">Signup</Nav.Link>
    </Nav>);

    return (user ? logedInMenu : publicMenu);
}

export default MainMenu;

The problem I have is that when I try to use this component:我遇到的问题是,当我尝试使用这个组件时:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom'
import Home from './Home';
import About from './About';
import Contact from './Contact';
import Login from './Login';
import Signup from './Signup';
import Dashboard from './Dashboard';
import Upload from './Upload';
import { getUser, removeUserSession } from './Utils/Common';
import MainMenu from './MainMenu';
import { Navbar, Container, Nav } from 'react-bootstrap';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
const mainMenu = MainMenu();
const user = getUser();

const userReducer = (state, action) => {
    switch (action.type) {
        case 'user/login':
            return {
                user: action.payload.user,
                token: action.payload.token
            }
        case 'user/logout':
            return {
                user: null,
                token: null
            }
        default:
            return {
                user: null,
                token: null
            }
    }
};

let store = createStore(userReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
const routing = (
    <Provider store={store}>
        <Navbar bg="light" expand="lg">
            <Container>
                <Navbar.Brand href="#home">Leeway Academy</Navbar.Brand>
                <Navbar.Toggle aria-controls="basic-navbar-nav" />
                <Navbar.Collapse id="basic-navbar-nav">
                    <Nav className="me-auto">
                        <Nav.Link href="/">Home</Nav.Link>
                        {mainMenu}
                    </Nav>
                </Navbar.Collapse>
            </Container>
        </Navbar>
        <BrowserRouter>
            <div>
                <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/about" element={<About />} />
                    <Route path="/contact" element={<Contact />} />
                    <Route path="/login" element={<Login />} />
                    <Route path="/signup" element={<Signup />} />
                    <Route path="/dashboard" element={
                        <RequireAuth redirectTo="/login">
                            <Dashboard />
                        </RequireAuth>
                    } />
                    <Route path="/upload" element={
                        <RequireAuth redirectTo="/login">
                            <Upload />
                        </RequireAuth>
                    } />
                </Routes>
            </div>
        </BrowserRouter>
    </Provider>
)

function RequireAuth({ children, redirectTo }) {
    return getUser() ? children : <Navigate to={redirectTo} />;
}

ReactDOM.render(routing, document.getElementById('root'));

I get this error:我收到此错误:

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)你可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. You might be breaking the Rules of Hooks您可能违反了 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.您可能在同一个应用程序中拥有多个 React 副本,请参阅https://reactjs.org/link/invalid-hook-call以获取有关如何调试和修复此问题的提示。

I don't understand why this is happening.我不明白为什么会这样。 I put together the login component using a seemingly similar approach and didn't have any problem.我使用看似相似的方法将登录组件放在一起,没有任何问题。

Could this mean React is not recognizing my function as a functional component?这是否意味着 React 没有将我的 function 识别为功能组件?

 const mainMenu = MainMenu();

You're calling MainMenu as a regular function when the module loads, and not as a component inside the React tree.当模块加载时,您将MainMenu作为常规 function 调用,而不是作为 React 树内的组件。

You need to get rid of that and use <MainMenu /> where you have {mainMenu}你需要摆脱它并在你有{mainMenu}的地方使用<MainMenu />

暂无
暂无

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

相关问题 React:为什么我不能将数据从一个功能组件传递到另一个功能组件? - React: Why can't I pass data from one functional component to another functional component? React 不会将我的 Context 组件视为功能组件。 收到无效挂钩调用错误 - React won't acknowledge my Context component as functional component. getting invalid hook call error React-redux:当它在功能组件中工作时,为什么我不能访问类组件中的状态属性? - React-redux: Why can't I access state properties in a class component, when it works in a functional component? 我如何调用/执行外部功能组件的 function 反应? - How can i call/execute function of functional component outside react? React 16.7具有状态挂钩,在任何情况下都可以使用功能组件而不是类组件吗? - React 16.7 has State Hook, can I use functional component instead of class component in any situation? 无法在反应中从自定义挂钩调用自定义挂钩 - Can't call custom hook from custom hook in react 从 npm 模块导入功能性反应组件返回无效的钩子调用 - Importing functional react component from npm modules returns invalid hook call 使用函数组件中的 useState 反应无效的挂钩调用错误 - React Invalid Hook Call Error with useState In Functional Component React - Invalid Hook Call:将 App 组件转换为功能组件,仍然得到 Invalid Hook Call - React - Invalid Hook Call: convert App component to functional component, still get Invalid Hook Call 收到此错误“无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。” 在反应功能组件内? - Getting this error “Invalid hook call. Hooks can only be called inside of the body of a function component.” inside a react functional component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM