简体   繁体   English

react.js应用程序中的无效钩子调用

[英]Invalid hook calls in react.js application

Having this error when running the program: 运行程序时出现此错误:

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 ap 发生这种情况可能是由于以下原因之一:1.您的React和渲染器版本可能不匹配(例如React DOM)2.您可能违反了《胡克规则》 3.您可能在其中包含多个React版本相同的ap

import React,  { Component } from "react";
import {useEffect,useState}  from "react";
import ReactDOM from 'react-dom'; 
const App = () => {
const APP_ID = "";
const APP_KEY = "";
const exapmle = "https://api.edamam.com/search? 
q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}";
  useEffect(()=>{
  console.log("effect has been");
  }); 

const [counter,setCounter] = useState(0);
return (
<div>
  <h1>hello world</h1>
  <form classname="search-form">
    <input classname="search_bar" type="text"></input>
    <button classname="search-button" type="submit">Search</button>
  </form>
  <h1 onClick = {()=> setCounter(counter+1)}> {counter}</h1>
</div>);};
export default App();

Try export default App instead of export default App() . 尝试export default App而不是export default App()

I made a few other tweaks you can test in CodeSandbox , namely: 您还可以在CodeSandbox中测试其他一些调整,即:

import React from 'react';
import { useEffect, useState } from 'react';
const App = () => {
  const APP_ID = '';
  const APP_KEY = '';
  const example = `https://api.edamam.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}`;
  useEffect(() => {
    console.log('useEffect will run once if I pass it a second argument of []');
    console.log(example);
    // eslint-disable-next-line
  }, []);

  const [counter, setCounter] = useState(0);
  return (
    <div>
      <h1>hello world</h1>
      <form className='search-form'>
        <input className='search_bar' type='text'></input>
        <button className='search-button' type='submit'>
          Search
        </button>
      </form>
      <h1 onClick={() => setCounter(counter + 1)}> {counter}</h1>
    </div>
  );
};
export default App;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM