我刚开始使用React,我试图导入一些虚拟XML进行循环。我发现有些人使用map()但是我遇到了问题,它没有返回任何内容或者出错。
可以在https://web-designer.ninja/jsfiddle/guestlist.xml
找到XML这是我的组件js:
import React, { Component } from 'react';
import XMLMapping from 'xml-mapping';
import axios from 'axios';
class Guests extends Component {
constructor(props) {
super(props);
this.state = {
guests: []
};
}
componentDidMount() {
axios.get('https://gist.githubusercontent.com/eMatsiyana/e315b60a2930bb79e869b37a6ddf8ef1/raw/10c057b39a4dccbe39d3151be78c686dcd1101aa/guestlist.xml')
.then(res => {
const xml = XMLMapping.load(res.data, { comments: false, arrays: [
'/dataset/record'
] });
var guests = XMLMapping.tojson(xml, {indent: true});
//console.log(xml);
this.setState({ guests });
//return guests;
});
}
render() {
function mapObject(object, callback) {
return Object.keys(object).map(function (key) {
return callback(key, object[key]);
});
}
return (
<div>
<div className="container">
<section className="section">
<h1 className="title">Guests attending Event A</h1>
<div className="columns">
{mapObject(this.state.guests, function (key, value) {
//return <div>Value: {value.record}</div>;
return <div key={key}>id: {value.record.first_name}</div>;
})}
</div>
</section>
</div>
</div>
);
}
}
export default Guests;
如果我取消注释这一行:return <div>Value: {value.record}</div>;
它在浏览器中抛出此错误:(猜测因为它是一个对象,但我似乎无法获得value.record.first_name或value.record [first_name])
任何帮助或指导将不胜感激!
更新
管理以使其与此一起使用:
{mapObject(this.state.guests, function (key, value) {
return <div>
{value.record.map((item,index) => {
console.log(item.first_name.$t)
return item.first_name.$t;
})}
</div>
})}
需要习惯反应句柄的返回方式。但如果有人能够解释为什么会这样,我肯定会接受答案。