React Hooks 与 Async/await
想象一下,你有一个文本框,可以根据你输入的内容列出 Google 书店中的书籍。如果没有符合你搜索条件的书籍,则显示“未找到书籍”。默认情况下,它始终显示“搜索书籍”。
场景:
1)无搜索:“搜索书籍”。2
)无结果:“未找到书籍”。3
)找到书籍:“显示书籍列表”。
在上述场景中,我们希望在Google API搜索主题后更新结果。这显然表明我们需要使用 Promise 或 Async/await 来实现结果。但在这里,我们希望创建一个自定义钩子,当点击搜索按钮时,该钩子会搜索书籍并显示结果。
现在的问题是,为什么我们要在这种情况下使用 hooks?答案很简单,因为我们希望代码更简洁,最终使用时只需一行代码即可。代码必须避免冗余,即遵循 DRY 原则(不要重复自己)。
function App() {
const [search, setSearch] = React.useState("");
const [query, setQuery] = React.useState("");
return (
<div className="App">
<h1>Search for Books on any Topic</h1>
<form
onSubmit={e => {
e.preventDefault();
setQuery(search);
}}
>
<label>Search : </label>
<input type="text" onChange={e => setSearch(e.target.value)} />
<input type="submit" value="search" />
</form>
<h1>List Result on {query}</h1>
</div>
);
到目前为止,这是我们用于获取状态“query”中最终搜索结果的简单代码。现在,我们将创建自定义异步钩子,以便在 Google API 上进行搜索。
function useAsyncHook(searchBook) {
const [result, setResult] = React.useState([]);
const [loading, setLoading] = React.useState("false");
React.useEffect(() => {
async function fetchBookList() {
try {
setLoading("true");
const response = await fetch(
`https://www.googleapis.com/books/v1/volumes?q=${searchBook}`
);
const json = await response.json();
// console.log(json);
setResult(
json.items.map(item => {
console.log(item.volumeInfo.title);
return item.volumeInfo.title;
})
);
} catch (error) {
setLoading("null");
}
}
if (searchBook !== "") {
fetchBookList();
}
}, [searchBook]);
return [result, loading];
}
我们不能将“async”关键字与“useEffect”回调方法一起使用,否则会导致竞态条件。
我们从 Google API 获取书籍,然后用书名更新 'setResult' 状态。React.useEffect 方法仅在 'searchBook' 发生更改时才会执行。
//Updated App Component
function App() {
const [search, setSearch] = React.useState("");
const [query, setQuery] = React.useState("");
const [result, loading] = useAsyncHook(query);
return (
<div className="App">
<h1>Search for Books on any Topic</h1>
<form
onSubmit={e => {
e.preventDefault();
setQuery(search);
}}
>
<label>Search : </label>
<input type="text" onChange={e => setSearch(e.target.value)} />
<input type="submit" value="search" />
</form>
{loading === "false" ? (
<h1>Search for Books</h1>
) : loading === "null" ? (
<h1>No Book Found</h1>
) : (
result.map(item => {
return <p>Book Title : {item}</p>;
})
)}
</div>
);
}
来源:因为人生只有一次
文章来源:https://dev.to/vinodchauhan7/react-hooks-with-async-await-1n9g
