【问题标题】:error: invalid hook call Hooks can only be called inside of the body of a function component错误:无效的钩子调用钩子只能​​在函数组件的主体内部调用
【发布时间】:2021-10-31 17:44:31
【问题描述】:

我正在尝试使用 useNavigate 转到另一个页面并在路径中传递 serviceID。任何想法为什么我会收到这个错误?

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();

const ProductCard = ({ props,product, ...rest }) => (
    <Card
  
    sx={{
      display: 'flex',
      flexDirection: 'column',
      height: '100%'
    }}
    {...rest}
  >
    <CardActionArea onClick={event => {navigate('app/service/'+product.serviceID)}}>
    
    <CardContent> ...

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    基于Rules of Hooks,需要将useNavigate()移动到组件内部:

    import { useNavigate } from 'react-router-dom';
    
    const ProductCard = ({ props,product, ...rest }) => {
    const navigate = useNavigate();  // <-- MOVE HERE
    return (
        <Card
      
        sx={{
          display: 'flex',
          flexDirection: 'column',
          height: '100%'
        }}
        {...rest}
      >
        <CardActionArea onClick={event => {navigate('app/service/'+product.serviceID)}}>
        
        <CardContent> ...
    

    【讨论】:

      【解决方案2】:

      错误很明显,钩子必须在组件内部调用,不能在外部调用。

      所以ProductCard功能组件必须这样重写:

      import { useNavigate } from 'react-router-dom';
      
      const ProductCard = ({ props,product, ...rest }) => { //<-- curly brackets
         const navigate = useNavigate(); //<-- call useNavigate
      
         return ( //<-- html inside return
            <Card
        
          sx={{
            display: 'flex',
            flexDirection: 'column',
            height: '100%'
          }}
          {...rest}
        >
          <CardActionArea onClick={event => {navigate('app/service/'+product.serviceID)}}>
          
          <CardContent> ...
         );
      }
      

      【讨论】:

        猜你喜欢
        • 2019-11-21
        • 2020-10-27
        • 2022-11-27
        • 2020-02-14
        • 2021-03-23
        • 2022-06-15
        • 2020-01-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多