在反应钩子中应该如何执行抓取?在这两个代码片段中,哪一个被称为最佳实践或执行 fetch 的最佳反应模式?
此示例用于执行操作。useEffectfetch
import React, { useState, useEffect } from "react";
export default function App() {
const [query, setQuery] = useState("");
const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
useEffect(() => {
if (!loading) return;
const fetchData = async () => {
const response = await fetch(
`https://api.github.com/search/repositories?q=${query}`
);
const data = await response.json();
setData(data.items);
setLoading(false);
};
fetchData();
}, [loading, query]);
const onSubmit = e => {
e.preventDefault();
setLoading(true);
};
return (
<div className="App">
<h1>Search Github Repo.</h1>
<h3>Implementation One</h3>
<form onSubmit={onSubmit}>
<input
type="text"
value={query}
onChange={e => setQuery(e.target.value)}
/>
<button type="submit">Search</button>
</form>
{loading && <div>Loading...</div>}
{!loading &&
data.map(repo => (
<div key={repo.id}>
<h4>{repo.name}</h4>
<p>{repo.description}</p>
</div>
))}
</div>
);
}
此示例使用事件处理程序来执行操作。onClickfetch
import React, { useState } from "react";
export default function App() {
const [query, setQuery] = useState("");
const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
const onSubmit = e => {
e.preventDefault();
setLoading(true);
const fetchData = async () => {
const response = await fetch(
`https://api.github.com/search/repositories?q=${query}`
);
const data = await response.json();
setData(data.items);
setLoading(false);
};
fetchData();
};
}
智慧大石
GCT1015
相关分类