首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用DEBOUNCING调用API后,应启动默认状态

使用DEBOUNCING调用API后,应启动默认状态
EN

Stack Overflow用户
提问于 2022-07-14 13:04:12
回答 1查看 47关注 0票数 0

通过将道具和回调函数传递给子组件和嵌套子组件,我创建了一个简单的"notes应用程序“。每次击键时,我的CRUD都能正常工作。但是,当我使用脱节概念调用API时,App.js会忘记状态并将其重新启动到默认值。

以下是代码-

App.js

代码语言:javascript
复制
 const addNote = async (note) => {
    const newNote = await CreateNote(note); // this is API call
    let newNotes = [...notes]; // notes is state - array of note object
    newNotes.unshift(newNote);
    setNotes(newNotes);
    setActiveNote(newNote);
  };

note-editor.js

代码语言:javascript
复制
    const handleNoteChange = (e) => {
        let newNote = { ...activeNote, [e.target.name]: e.target.value };
        activateNote(newNote);
        //addOrUpdateNote(newNote); // this code is working and updating the list correctly
        optimizedAddOrUpdateNote(newNote); // this code re-initiates the "notes" state in App.js to default []
    };


    const addOrUpdateNote = (note) => {
        if (!note.createdDate) {
            if (note.title.trim() || note.body.trim()) {
                addNote(note); // this is coming from app.js as prop callback
            }
        } else {
            updateNote(note); // this is coming from app.js as prop callback
        }
    };



    const debounce = (func) => {
       let timer;
       return function(...args) {
        const context = this;
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            timer = null;
            func.apply(context, args);
        }, 500);
      }
    }

    const optimizedAddOrUpdateNote = useCallback(debounce(addOrUpdateNote), []);

    return (
             <div className={Classes["note-editor-body"]}>
                <input
                    type='text'
                    name='title'
                    placeholder='title...'
                    onChange={handleNoteChange} //trying to call the API using debounciing
                    value={activeNote.title}
                />
                <textarea
                    maxLength={AppConstants.NOTE_BODY_CHARACTER_LIMIT}
                    name='body'
                    placeholder='add your notes here'
                    onChange={handleNoteChange} //trying to call the API using debounciing
                    value={activeNote.body.slice(
                        0,
                        AppConstants.NOTE_BODY_CHARACTER_LIMIT
                    )}
                />
            </div>
         )

任何帮助都将不胜感激。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2022-07-14 13:30:45

React有自己的构建,可以使用useDeferredValue()来破坏功能。这里有一篇很好的文章:https://blog.webdevsimplified.com/2022-05/use-deferred-value/

因此,在您的示例中,您可以将optimizedAddOrUpdateNote函数替换为具有依赖于deferredValue的useEffect钩子。就像这样:

代码语言:javascript
复制
import { useState, useDeferredValue, useEffect } from "react";

export default function App() {
  const [note, setNote] = useState("");
  const deferredNote = useDeferredValue(note);

  useEffect(() => {
    console.log("call api with deferred value");
  }, [deferredNote]);

  function handleNoteChange(e) {
    setNote(e.target.value);
  }

  return (
    <>
      <input type="text" value={note} onChange={handleNoteChange} />
      <p>{note}</p>
    </>
  );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72980990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档