I have button click system and it works.
function clickCreate(msg){
console.log(msg);
}
const CreateButton = (props) =>{
return(
<div>
<i onClick = {() => clickCreate("test")} id="createBtn" className="fas fa-5x fa-microphone-alt"></i>
</div>
);
}
Now I want to fetch the API inside the function.
So, change the function clickCreate
like this
function clickCreate(msg){
const [result, setResult] = useState([]);
useEffect(() => {
axios.get('http://localhost:8000/api/genres/')
.then((res)=> {
console.log(res.data.items);
setResult(res.data.items);
}).catch(err=>{console.log(err);});
}, []);
}
However there comes error like this.
I should not use useState and useEffect in function, but how can trigger the API by btn click??
./src/views/Components/Components.js
Line 168:31: React Hook "useState" is called in function "clickCreate" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
Line 170:3: React Hook "useEffect" is called in function "clickCreate" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
Search for the keywords to learn more about each error.
question from:
https://stackoverflow.com/questions/65643375/react-hook-usestate-is-called-in-function 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…