运行程序时出现此错误:
无效的挂钩调用。钩子只能在 功能组件。可能发生以下情况之一 原因: 1.您的React和渲染器版本可能不匹配(例如React DOM) 2.您可能违反了《钩子规则》 3.您可能在同一ap中有一个以上的React副本
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();
答案 0 :(得分:0)
尝试使用export default App
代替export default App()
。
我还可以进行其他一些调整,test in CodeSandbox,即:
example
中的embed template literals使用反引号useEffect
to a single execution,添加第二个参数[]
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;