javascript - 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
的代码,不显示平面文本。
请有任何建议。
解决方案
以我的经验,这是因为 Product.desc 是以异步方式获取的,因此在某些时候它是未定义的。因此,当 renderHTML 尝试获取长度时,它会在获取完成之前的某个时间点尝试获取 undefined 的长度。
尝试这个:
<Descriptions.Item label="Description">
{Product.desc ? <div>{renderHTML(Product.desc)}</div> : null}
</Descriptions.Item>
推荐阅读
- sql-server - 如何在 SQL Server 中显示同一个人拥有所有颜色代码?
- python - 为什么 if 语句的语法无效?
- c# - App.Config PostgreSQL Entity Framework 6 的 Npgsql C# 问题
- python-3.x - 如何在 Python 上使用 rawpy 读取图片的 RGB 值
- python - 如果条件为真,我如何比较变量然后分配一个新值?
- git - 带有奇怪分支的 SVN 到 Git 迁移
- java - Java 的未来
- normalization - “规范化”和“规范化”数据之间是否存在明确的区别?
- vue.js - 当值使用计算数据时,如何在 type=Number 上使用货币?
- html - 显示前 2 个 flex 项目彼此居中且顶部对齐