【问题标题】:React-quilljs: TypeError: Cannot read properties of undefined (reading 'length')React-quilljs:TypeError:无法读取未定义的属性(读取 \'length\')
【发布时间】:2022-08-14 11:44:15
【问题描述】:

我正在使用react-quilljs 请参阅设置“使用初始值”的文档。使用他们的文档可以正常工作,直到您尝试使用 useEffect 从数据库中提取初始值。我不断收到错误TypeError:无法读取未定义的属性(读取\'length\')从下面的这行代码:

quill.clipboard.dangerouslyPasteHTML(savedIntroText);

知道如何正确解决这个问题吗?

  const [savedIntroText, setSavedIntroText] = useState();

// Getting text in from database
    useEffect(() => {
      const fetchResults = async () => {
        const result = await axios({
          method: \"GET\",
          url: \"http://localhost:4000/userData\",
          withCredentials: true,
        });
        setSavedIntroText(result.data.introEssayText);
      };
      fetchResults();
    }, []);
    
    //Setting initial Quill value here, as shown in docs:
    if (quill) {
      quill.clipboard.dangerouslyPasteHTML(savedIntroText);
    }
    
    const handleUpdatedIntro = () => {
      const text = quill.getText();
      setSavedIntroText(text);
    };
    
    // ===== Implementing Quill ======
    
    <div ref={quillRef} onInput={handleUpdatedIntro} />;

    标签: reactjs axios quill react-state react-quill


    【解决方案1】:

    使用您当前的代码,在为 savedIntroText 设置任何值之前调用 quill.clipboard.dangerouslyPasteHTML(savedIntroText); (因此您会看到未定义的错误)。如果您希望在 API 检索到后粘贴该值,请尝试在加载数据后将其移动到您的 useEffect,例如:

    useEffect(() => {
      const fetchResults = async () => {
        // Only request/load data once quill is loaded
        if (!quill) {
          return;
        }
        const result = await axios({
          method: "GET",
          url: "http://localhost:4000/userData",
          withCredentials: true,
        });
        quill.clipboard.dangerouslyPasteHTML(result.data.introEssayText);
      };
      fetchResults();
    }, [quill]);
    

    【讨论】:

    • 这解决了未定义的错误,但这不起作用,因为在此运行之前 quill 不会加载。知道如何解决这个问题吗?
    猜你喜欢
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多