【发布时间】:2020-05-15 10:28:34
【问题描述】:
我的组件通过调用包含通过 API 请求的逻辑的钩子文件来获取数据。 默认情况下,它将调用 API,无需任何额外参数。 在 GUI 中,我还显示了一个输入,用户可以在其中输入文本。 每次他写一封信我都想重新获取数据。但我不太确定如何使用 react 和 hooks 来做到这一点。
我声明了“useEffect”。我看到输入的内容发生了变化。但还有什么?我不能从那里调用钩子函数,因为我得到了这个错误:
“不能在回调中调用 React Hook “useFetch”。必须在 React 函数组件或自定义 React Hook 函数 react-hooks/rules-of-hooks 中调用 React Hooks”
这是代码:
hooks.js
import { useState, useEffect } from "react";
function useFetch(url) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchUrl() {
const response = await fetch(url);
const json = await response.json();
setData(json);
setLoading(false);
}
fetchUrl();
}, [url]);
return [data, loading];
}
export { useFetch };
mycomponent.js
import React, { useState, useEffect } from 'react';
import { useFetch } from "../hooks";
const MyComponent = () => {
useEffect(() => {
console.log('rendered!');
console.log('searchTerm!',searchTerm);
});
const [searchTerm, setSearchTerm] = useState('');
const [data, loading] = useFetch(
"http://localhost:8000/endpoint?${searchTerm}"
);
return (
<>
<h1>Users</h1>
<p>
<input type="text" placeholder="Search" id="searchQuery" onChange={(e) => setSearchTerm(e.target.value)} />
</p>
{loading ? (
"Loading..."
) : (
<div>
{data.users.map((obj) => (
<div key={`${obj.id}`}>
{`${obj.firstName}`} {`${obj.lastName}`}
</div>
))}
</div>
)}
</>
);
}
export default MyComponent;
【问题讨论】:
-
您是否尝试将其导出为默认值?
-
是的,它仍然给出同样的错误。
标签: reactjs react-hooks