首页 > 解决方案 > 尝试在类组件中使用功能组件时出错

问题描述

我有两个主要组成部分。Recipe.js 组件是父组件,RecipeCard.js 是子组件。我收到错误错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。我不确定为什么会收到此错误。我希望我能对问题所在有所了解。

食谱.js:

import React, { Component } from "react";
import AddRecipe from "./addRecipe";
import "./Recipe.css";
import { Route, BrowserRouter as Router, Switch, Link } from "react-router-dom";
import { useAuth0 } from "@auth0/auth0-react";
import RecipeCard from "./RecipeCard";

class Recipe extends Component {
  constructor() {
    super();
    this.state = {
      recipes: [], // State array to hold recipe objects that are fetched from the database
      search: ''
    };
  }
  updateSearch(event) {
    this.setState({ search: event.target.value.substr(0, 20) });
  }

  componentDidMount() {
    fetch("/getRecipes") //Api call using route from server.js to obtain recipe data
      .then((res) => res.json())
      .then((recipes) =>
        this.setState(
          { recipes },
          () =>
            //inserts data to the state array of the component
            console.log("recipes fetched...", recipes) //confirm that the recipes were fetched in the console
        )
      );
  }

  render() {
    let filteredRecipes = this.state.recipes.filter(
      (recipe) => {
        return recipe.recipeName.toLowerCase().indexOf(this.state.search) !== -1;
      }
    );
    return (
      <Router>
        <div>
          <input type="text" value={this.state.search} onChange={this.updateSearch.bind(this)}></input>
          <ul>
            {filteredRecipes.map((
              recipe //iterate through each recipe object in the state array display the id, name and instructions of each recipe
            ) => (

                <li className="Recipes" key={recipe.idrecipe}>
                  <RecipeCard imgUrl={recipe.imgUrl} id={recipe.idrecipe} name={recipe.recipeName} instructions={recipe.recipeInstruction} />
                  

                </li>
              ))}
          </ul>
          <Switch>
            <Route path="/addRecipe">
              <AddRecipe />
            </Route>
          </Switch>
        </div>
      </Router>
    );
  }
}
export default Recipe; //Export the recipe component to be used in the main index.js file

食谱卡.js:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';

const useStyles = makeStyles({
    root: {
        maxWidth: 345,
    },
    media: {
        height: 140,
    },
});

export default function RecipeCard(props) {
    const classes = useStyles();

    return (
        <Card className={classes.root}>
            <CardActionArea>
                <CardMedia
                    className={classes.media}
                    image={props.imgUrl}
                    title=""
                />
                <CardContent>
                    <Typography gutterBottom variant="h5" component="h2">
                        {props.name}
                    </Typography>
                    <Typography variant="body2" color="textSecondary" component="p">
                        {props.instructions}
                    </Typography>
                </CardContent>
            </CardActionArea>
            <CardActions>
                <Button size="small" color="primary">
                    Share
        </Button>
                <Button size="small" color="primary">
                    Learn More
        </Button>
            </CardActions>
        </Card>
    );
}

标签: reactjsmaterial-ui

解决方案


钩子只能用在功能组件中。

Recipe.js是一个组件,它从React.Component.

这就是为什么useAuth0会失败,因为它是一个钩子。

你现在有两个选择。您可以将您的组件更改Recipe.js为功能组件,也可以使用useAuth0我猜想是Higher-Order-Component@auth0/auth0-react 提供的替代方法。

withAuth0可能是一个不错的选择。

参考:

https://auth0.com/docs/libraries/auth0-react#use-with-a-class-component

https://reactjs.org/docs/hooks-intro.htm


推荐阅读