gpt4 book ai didi

javascript - 无效的钩子(Hook)调用按钮来提交表单

转载 作者:行者123 更新时间:2023-11-28 12:52:33 25 4
gpt4 key购买 nike

我有一个按钮,用于向 API 提交表单。我收到错误:

Error: Invalid hook call. Hooks can only be called inside of the body of a function...

我的整个代码在这里:

function SubmitButton(props) {
function SendData(url) {
const [data, setData] = useState([]);
const eta = document.getElementById('eta_value')
async function getData() {
const options ={
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({
name:'26',
eta:'30',
})
}
const response = await fetch(url, options)
.then(response =>{
console.log(response.status);
});
}
useEffect(() => {//check this out
getData();
}, []);
};
const title = props.title;
//const onSubmit = {SendData}
return(
<div id={title}>
<Button
onClick={() => SendData("http://XXX.X.X.X:XXXX/api/")}
variant="contained"
color="primary">
</Button>
</div>
)
}
export default SubmitButton

它显示错误源自:

function SendData(url) {
const [data, setData] = useState([]);
const eta = document.getElementById('eta_value')
async function getData() {

这是由 onClick 调用的。我排查了好几天的问题,但无法弄清楚为什么我违反了钩子(Hook)规则。

最佳答案

问题是您在嵌套函数(您的 sendData() 函数)中使用 useState Hook 。

作为Rules of Hooks文档内容如下:

Only Call Hooks at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)

要解决此问题,请将 const [data, setData] = useState([]); 语句和 useEffect() Hook 移动到函数的顶层成分。

希望这有帮助。

关于javascript - 无效的钩子(Hook)调用按钮来提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59829250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com