javascript - 我如何在 React 中实现输入更改的去抖动自动保存?
问题描述
所以问题是假设你有一个编辑器。
用户一直在编辑器中输入,他会闲置一段时间,比如 5 秒。所以闲置5秒后,你向api发出网络请求,将他输入的内容保存在数据库中。它应该在空闲 5 秒后只发出一个请求。
我完成了,但它提出的请求等于字数。如果你输入 like 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;
解决方案
问题是每次渲染都会创建一个新的去抖动函数,因此 API 会被多次调用。您必须使用useCallback
来记忆去抖动功能。如果你想在 debounced 函数中使用,你可以在调用时editorState
从方法中传递它。您还需要更正您的去抖动语法onEditStateChange
debounced
const EditorComponent = () => {
const [editorState, setEditorState] = React.useState(
EditorState.createEmpty()
);
// I need another logic that checks the time difference of idling.
const debounced = useCallback(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;
推荐阅读
- .net - 使用 Utf8JsonReader 读取整个嵌套数组
- android - BiometricPrompt 在一段时间后消失或消失
- linux - 访问控制列表 (ACL) 是什么时候出现在 Unix/Linux 上的?
- c++ - 错误 C2064:术语不计算为采用 3 个参数的函数
- codeigniter-3 - Codeigniter 所有路由都不起作用,除了默认
- c# - 如何使用 forEach 循环对象数组?
- nativescript - NativeScript Angular - 服务器发送事件
- postgresql - 验证具有不同日期格式的列中的日期格式
- java - 在 jsp 中上传文件并在 servlet 中调用该文件
- java - 在 Spring @RequestBody 中访问动态添加的属性