![](/img/trans.png)
[英]I have this React Invalid Hook Call Error that I'm getting and I wanted to see if I was breaking the rules of hooks or is it something else?
[英]Can anyone see why I'm getting an "invalid hook" error? I have tried and tried and can't see what the problem is
我是 React 的新手,但早些時候我改變了一些東西,無論我如何將我的代碼剝離到鈎子的基本基礎,我似乎都無法逃脫這個錯誤..
無效的掛鈎調用。 鈎子只能在函數組件的主體內部調用。 這可能由於以下原因之一而發生:
這是我的 React 函數組件...]
import { useState } from "react";
export function GetPokemonInfo() {
const [pokemonState, setPokemonState] = useState();
let number = 1;
setPokemonState(number * 2);
console.log(pokemonState);
return (
<div>
<p>Hi</p>;
</div>
);
}
GetPokemonInfo();
我應該補充一點,我使用 create-react-app 啟動了該應用程序,並且除了主應用程序和這個組件之外,沒有其他組件呈現。
錯誤的出現是由於錯誤的組件實現(組件的實現是通過使用組件作為 JSX 標記,如<GetPokemonInfo />
)並且您調用GetPokemonInfo()
其中 GetPokemonInfo 是一個功能組件,其中有一個useState
鈎子。 當你刪除它時,錯誤就會消失,但你仍然有另一個問題。
如果要初始化pokemonState
,只需將 setState 包裝在 useEffect 中,無需依賴。
useEffect(() => {
const number = 1;
setPokemonState(number * 2);
}, []);
如果你想觀察狀態變化,只需使用 useEffect 塊來包裝你的 console.log。 console.log 將在任何 pokemonState 更改時調用,而不是在每次渲染時調用。
useEffect(() => {
console.log(pokemonState);
}, [pokemonState]);
您的 GetPokemonInfo 組件將變為:
import { useEffect, useState } from "react";
export function GetPokemonInfo() {
const [pokemonState, setPokemonState] = useState();
useEffect(() => {
const number = 1;
setPokemonState(number * 2);
}, []);
useEffect(() => {
console.log(pokemonState);
}, [pokemonState]);
return (
<div>
<p>Hi</p>;
</div>
);
}
並將其導入到父組件中:
import GetPokemonInfo from './GetPokemonInfo'
...
function YourParentComponent() {
...
return (
...
<GetPokemonInfo />
...
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.