首页 > 解决方案 > react-render-html:TypeError:无法读取未定义的属性“长度”

问题描述

我需要用 制作一个气泡富文本编辑器react-quill,当我尝试用富编辑器制作内容时,它工作得很好。但是当我尝试从我的数据库中获取数据时,react-render-html它不起作用,显示如下错误:

TypeError: Cannot read property 'length' of undefined
push../node_modules/react-render-html/node_modules/parse5/lib/tokenizer/preprocessor.js.module.exports.push../node_modules/react-render-html/node_modules/parse5/lib/tokenizer/preprocessor.js.Preprocessor.write
C:/Users/alami/OneDrive/Desktop/MERN stack/online shopping/client/node_modules/react-render-html/node_modules/parse5/lib/tokenizer/preprocessor.js:91
  88 |     else
  89 |         this.html = chunk;
  90 | 
> 91 |     this.lastCharPos = this.html.length - 1;
  92 |     this.endOfChunkHit = false;
  93 |     this.lastChunkWritten = isLastChunk;
  94 | };

我已经通过这种方式尝试过代码:

import React, { useEffect, useState } from "react";
import { Button, Descriptions } from "antd";
import renderHTML from "react-render-html";

function ProductInfo(props) {
  const [Product, setProduct] = useState({});
  useEffect(() => {
    setProduct(props.detail);
  }, [props.detail]);

  return (
    <div>
      <Descriptions title="Product Info">
        <Descriptions.Item label="Price">${Product.price}</Descriptions.Item>
        <Descriptions.Item label="Sold">{Product.sold}</Descriptions.Item>
        <Descriptions.Item label="View">{Product.views}</Descriptions.Item>
        <Descriptions.Item label="Description">
          <div>{renderHTML(Product.desc)}</div>
        </Descriptions.Item>
      </Descriptions>

      <br />
      <br />
      <br />
      <div style={{ display: "flex", justifyContent: "center" }}>
        <Button shape="round" type="danger">
          Contact me
        </Button>
      </div>
    </div>
  );
}

export default ProductInfo;

renderHTML如果我从那时删除{renderHTML(Product.desc)}它可以工作,但输出显示我html的代码,不显示平面文本。

请有任何建议。

标签: javascriptnode.jsreactjs

解决方案


以我的经验,这是因为 Product.desc 是以异步方式获取的,因此在某些时候它是未定义的。因此,当 renderHTML 尝试获取长度时,它会在获取完成之前的某个时间点尝试获取 undefined 的长度。

尝试这个:

<Descriptions.Item label="Description">
          {Product.desc ? <div>{renderHTML(Product.desc)}</div> : null}
        </Descriptions.Item>

推荐阅读