React使用react-xml-parser解析XML遇TypeError错误求助
解决React组件中XML解析的TypeError问题
我尝试在React组件中获取XML文件,但使用XMLParser时抛出错误:
There is an error , TypeError: Cannot read properties of undefined (reading 'replace') at e.value (bundle.js:1:1) at e.value (bundle.js:1:1) at BlogFeed.js:19:1
组件代码如下:
import React, { useEffect, useState, Component } from "react"; import axios from "axios"; import ReactDOM from "react-dom"; import XMLParser from 'react-xml-parser'; import { parse } from 'fast-xml-parser'; // import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader // import { Carousel } from "react-responsive-carousel"; import "./sample.scss"; const BlogFeed = () => { const [data , setData] = useState(); useEffect(() => { axios .get("https://7targets.ai/blog/feed.xml", { "Content-Type": "application/xml; charset=utf-8", }) .then((response) => { setData(response.data) var xml = new XMLParser().parseFromString(data); // Assume xmlText contains the example XML console.log(xml); }).catch((error)=>{ console.log("There is an error , ",error) }); }, []); console.log(data); return ( <> </> ); }; export default BlogFeed;
错误原因
- state更新异步特性:
setData是异步操作,调用setData(response.data)后,data不会立刻更新为新值,此时data仍为初始的undefined,传入parseFromString自然会触发报错。 - 请求头设置错误:GET请求中设置
Content-Type头不合适,应该用Accept头指定期望接收的响应类型。
解决方案
方案1:直接使用响应数据解析
跳过state的异步更新,直接用axios返回的原始响应数据解析:
useEffect(() => { axios .get("https://7targets.ai/blog/feed.xml", { headers: { "Accept": "application/xml; charset=utf-8", // 替换为Accept头 }, }) .then((response) => { const xmlData = new XMLParser().parseFromString(response.data); console.log(xmlData); setData(xmlData); // 解析后的数据存入state供后续使用 }).catch((error)=>{ console.log("There is an error , ",error) }); }, []);
方案2:监听state变化后解析
如果需要先存储原始XML,再后续解析,可添加监听state的useEffect:
const BlogFeed = () => { const [rawXml, setRawXml] = useState(); const [parsedData, setParsedData] = useState(); useEffect(() => { axios .get("https://7targets.ai/blog/feed.xml", { headers: { "Accept": "application/xml; charset=utf-8", }, }) .then((response) => { setRawXml(response.data); }).catch((error)=>{ console.log("There is an error , ",error) }); }, []); // 当rawXml存在时执行解析 useEffect(() => { if (rawXml) { const xml = new XMLParser().parseFromString(rawXml); console.log(xml); setParsedData(xml); } }, [rawXml]); console.log(parsedData); return ( <> </> ); };
方案3:替换为fast-xml-parser解析
你已导入fast-xml-parser,它的稳定性和性能更优,可直接使用:
useEffect(() => { axios .get("https://7targets.ai/blog/feed.xml", { headers: { "Accept": "application/xml; charset=utf-8", }, }) .then((response) => { const parseOptions = { ignoreAttributes: false, parseNodeValue: true, }; const parsedResult = parse(response.data, parseOptions); console.log(parsedResult); setData(parsedResult); }).catch((error)=>{ console.log("There is an error , ",error) }); }, []);
内容的提问来源于stack exchange,提问作者Tanvesh
相关产品推荐
相关产品推荐

