【发布时间】:2019-09-21 16:19:11
【问题描述】:
所以问题是假设您有一个编辑器。
用户一直在编辑器中输入,他会闲置一段时间,比如 5 秒。所以闲置5秒后,你向api发出网络请求,将他输入的内容保存在数据库中。它应该在空闲 5 秒后只发出一个请求。
我完成了,但它发出的请求等于字数。如果你像 asdf 这样输入,它会发出四个 api 请求。在我的例子中,四个console.log();
const EditorComponent = () => {
const [editorState, setEditorState] = React.useState(
EditorState.createEmpty()
);
// I need another logic which checks the time difference of idling.
const debounced = () => {
return debounce(() => {
console.log("the api is going to call after 5 seconds");
}, 5000);
};
const onEditorStateChange = value => {
const rawContent = convertToRaw(value.getCurrentContent());
const markdown = draftToMarkdown(rawContent);
setEditorState(value);
debounced()
};
return (
<div style={{ width: "500px" }}>
<Editor
editorState={editorState}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
onEditorStateChange={onEditorStateChange}
/>
</div>
);
};
export default EditorComponent;
【问题讨论】:
-
尝试 const debounced = debounce(() => { console.log("API 将在 5 秒后调用"); }, 5000); };
-
@VivekN 伙计,这正是我所做的。还是我错过了什么?
-
观察他写的代码,他立即执行了 debounce,而不是放在一个函数中,你在这里所做的是你正在创建一个新的 debounce 函数,每次你调用 debounced 方法时,debounce(function ) 提供了一个可以在 onEditorStateChanged 中使用的函数
标签: javascript reactjs lodash react-hooks debounce