[英]Invalid hook call. Hooks can only be called inside of the body of a function component. How to solve this issue?
[英]Invalid hook call. Hooks can only be called inside of the body of a function component. - When using state
我正在構建一個博客應用程序,我正在嘗試將參數發送到另一個功能組件,並且還嘗試在調用時使用useState
設置 state,但是當我單擊按鈕發送參數時, Argument is successfully working (sending to component)
但State is not setting
通過useState
設置。
每次我定義useState
時都會顯示錯誤。
未捕獲的錯誤:無效的掛鈎調用。 鈎子只能在 function 組件的主體內部調用。 這可能由於以下原因之一而發生:
- 你可能有不匹配的 React 版本和渲染器(例如 React DOM)
- 您可能違反了 Hooks 規則
- 你可能在同一個應用程序中擁有多個 React 副本
我已經嘗試了很多次,但它仍然無法正常工作。
應用程序.js
function App() {
const sendArgument = () => {
AnotherComponent("argument_1")
}
return (
<div>
<button type="button" onClick={sendArgument}>Send Argument</button>
</div>
)
}
function AnotherComponent(arg_1) {
// Error shows when I define useState here...
const [isOpen, setIsOpen] = useState(false);
// Argument is successfully showing
console.log(arg_1)
// Set to true when fucntional component calls from another component
setIsOpen(true)
const setBooleanTrue = () => {
setIsOpen(false)
}
return (
<div>
<button type="button" onClick={setBooleanTrue}>Set state</button>
</div>
)
}
它一直顯示該錯誤,並且沒有設置 state,當我刪除useState
時,沒有顯示錯誤。
任何幫助將非常感激。 先感謝您
我們不能在嵌套的 function 中調用鈎子,這是因為 AnotherComponent 位於 sendArgument function 中。
您可以在 App Component 本身的 return function 中渲染 anotherComponent 。 在 App 組件本身中定義 state 並將其作為 prop 發送給 AnotherComponent。
我認為您可以在嵌套組件/函數中使用 state。 我沒有您的代碼的確切上下文,但基於您的代碼片段在這里我重構了您的代碼。
import { useState } from "react";
export default function App() {
const [argToSend, setArgToSend] = useState();
const sendArgument = () => {
setArgToSend("Some Argument");
};
return (
<div>
<button type="button" onClick={sendArgument}>
Send Argument
</button>
<AnotherComponent arg={argToSend} />
</div>
);
}
function AnotherComponent({ arg }) {
// Another component's own state
const [isOpen, setIsOpen] = useState(false);
const setBooleanTrue = () => {
setIsOpen(!isOpen);
};
return (
<div>
<h4>
Argument received from Another component:-
<span style={{ color: "red" }}>{arg}</span>
</h4>
<h3>{isOpen ? "True" : "False"}</h3>
<button type="button" onClick={setBooleanTrue}>
Set state
</button>
</div>
);
}
正如 Parth 所建議的,您應該將數據從一個組件作為道具發送到另一個組件另外我建議您使用任何代碼格式化程序希望這會有所幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.