尝试在类组件中使用功能组件时出现错误

时间:2020-11-09 02:33:07

标签: reactjs material-ui

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

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

RecipeCard.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>
    );
}

1 个答案:

答案 0 :(得分:1)

挂钩只能在功能组件中使用。

您的Recipe.js是一个组件,它从React.Component开始扩展。

这就是useAuth0失败的原因,因为它是一个钩子。

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

withAuth0可能是一个很好的选择。

参考资料:

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

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