【发布时间】:2021-10-18 14:53:21
【问题描述】:
在我的子方法之一上调用 useEffect 函数时,结果
ReactJS : 无效的钩子调用。 Hooks 只能在内部调用 函数组件的主体。
流动
onClick(message) --> call CallGetAMIDetails(message) --> Call Loaddata(message) --> Perform REST Call and -->Returns Array of String
但是我的类已经是函数组件了
import React, {useEffect, useState} from 'react';
import {DashboardLayout} from '../components/Layout';
import Select from 'react-select'
const options = [
{value: 'ami-abc*', label: 'ami-abc'},
{value: 'ami-xyz*', label: 'ami-xyz'},
]
const DiscoverAMIPage = () => {
function Loaddata() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
fetch("http://localhost:10000/connections")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return []
} else if (!isLoaded) {
return []
} else {
return (
items
);
}
}
function CallGetAMIDetails(message) {
return Loaddata(message)
}
const [message, setMessage] = useState('');
const [items, setItems] = useState([]);
return (
<DashboardLayout>
<h2>Discovered AMI</h2>
<Select
onChange={e => {
setMessage(e.value);
setItems(CallGetAMIDetails(e.value));
}}
options={options}
/>
{console.log("----")}
<h2>{items}</h2>
{console.log("----")}
</DashboardLayout>
)
}
export default DiscoverAMIPage;
我在这里做错了什么?
【问题讨论】:
-
我认为由于
Loaddata被调用,react 并不认为它是一个组件,而是一个常规的 JS 函数。见Only call hooks from react functions -
错误告诉你你在做什么——钩子只能在组件函数的“顶层”调用,但你在 Loaddata() 函数中调用 useEffect(),即不是您的 DiscoverAMI 组件的顶层
-
我会说清楚的。发生这种情况是因为您在“DiscoverAMIPage”中有“Loaddata”
标签: javascript reactjs