【发布时间】:2021-03-25 14:05:52
【问题描述】:
我有一个搜索栏,我在其中获取输入的文本并进行 API 调用。为了限制 API 调用的数量,我使用了 debounce。我想在搜索栏中输入内容时显示加载器,但由于去抖动,该操作也被延迟。我试图在下面的代码中复制行为-
import React, { useState } from "react";
import "./style.css";
import { debounce } from "lodash";
export default function App() {
const [loading, setLoading] = useState(false);
const callAPI = () => {
setLoading(true);
// Post this will be the logic to call API
console.log('API is called')
};
const inputChangeHandler = event => {
const text = event.target.value;
if (text.length === 0) {
setLoading(false);
} else {
callAPI();
}
};
const debouncedChangeHandler = debounce(inputChangeHandler, 1000);
return (
<div>
<input type="text" onChange={debouncedChangeHandler} />
{loading && <p>Loading...</p>}
</div>
);
}
Here是链接
我想在搜索栏中输入内容时显示加载程序,但我也想消除 API 调用的调用。
【问题讨论】: