无法在我的 ReactJS 应用程序中使用 useNavigate 导航到另一个网页

Unable to navigate to another web page using useNavigate in my ReactJS app

我正在尝试使用 'useNavigate' 导航到其他网页。我收到以下错误消息,但我不太明白自己做错了什么。请问有人可以指教吗?

import React from 'react';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
import { useNavigate } from 'react-router-dom';

import SendIcon from '@mui/icons-material/Send';

const Header = () => {

  const SendMessage = () => {
  console.log('Send message!');
  const navigate = useNavigate();
  navigate('/writeMessage');

}
 return (
<Box sx={{ flexGrow: 1 }}>
  <AppBar position="static">
    <Toolbar>
      <IconButton
        size="large"
        edge="start"
        color="inherit"
        aria-label="menu"
        sx={{ mr: 2 }}
      >
        <MenuIcon />
      </IconButton>
      <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
        MyApp
      </Typography>
        <SendIcon sx={{ marginRight: "20px" }} onClick={SendMessage}> 
        </ SendIcon>
      <Button variant="contained" >Connect Wallet</Button>
    </Toolbar>
  </AppBar>
</Box>
);
}

导出默认值 Header;

控制台:

Uncaught 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.

您正在嵌套函数中调用 useNavigate 挂钩。这打破了 Rules of Hooks 之一,“不要在循环、条件或嵌套函数中调用 Hooks。”

将其移动到组件范围。

const Header = () => {
  const navigate = useNavigate();

  const SendMessage = () => {
    console.log('Send message!');
    navigate('/writeMessage');
  };

  ...