反应:遍历对象,查找数组,并显示数组项 [英] React: Iterate over object, find array, and display array items
本文介绍了反应:遍历对象,查找数组,并显示数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试遍历axios调用"/Home/NewsNotes"返回的对象.
I'm trying to iterate over an object being return by the axios call to "/Home/NewsNotes".
来自Axios的响应
Response from Axios
我可以在屏幕上显示属性名称,但是在访问"NewsNotes"数组时遇到问题.
I'm able to display the property names to the screen, but I'm having issues accessing the "NewsNotes" array.
这是我的组件代码.
class ReleaseDetailsComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
releaseNotes: {}
};
}
componentDidMount() {
var _this = this;
const urlParams = new URLSearchParams(window.location.search);
const currCatId = urlParams.get('categoryId');
axios.get('/Home/NewsNotes?categoryId=' + currCatId)
.then(response => _this.setState(
{ releaseNotes: response.data }
))
.catch(function (error) {
console.log(error);
});
console.log(currCatId);
}
render() {
return (
<section>
<div className="row">
<div className="col-sm-8 col-sm-offset-2 col-md-10 col-md-offset-1">
<h2 className="page-title tutorials"><img className="title-icon" src="/Content/images/icons/icon-release-notes.png" /> News & Release Notes</h2>
<h3>{this.state.releaseNotes.Title}</h3>
{Object.keys(this.state.releaseNotes).map(function (item, key) {
return (
<p>{item}</p>
);
})}
</div>
</div>
</section>
);
}
}
ReactDOM.render(
<ReleaseDetailsComponent />,
document.getElementById('tutorialsWrapper')
);
推荐答案
我假设您使用axios从URL检索的对象看起来像:
I assume the object which you retrieved from URL using axios will look like:
var releaseNotes = {
NewsNotes: [
"Buy some milk": "data 1",
"Clean kitchen": "data 2",
"Watch Netflix": "data 3"
],
NewsNotesCategoryId: 3,
SortOrder: null,
Title: "1.0.1",
TypeId: 2
};
接下来,您可以按如下方式将"this"注入map方法,检查是否有任何子数组,然后将每个JSX块推入temp数组中以便稍后返回:
Next, you can inject "this" into map method as follow, check for any child array, then push each JSX block into the temp array in order to return later:
{Object.keys(this.state.releaseNotes).map((key, idx) => {
var temp = [];
temp.push(<p>{key}</p>);
if (Array.isArray(this.state.releaseNotes[key])) {
this.state.releaseNotes[key].map(ckey => {
temp.push(<p>{ckey}</p>);
});
}
return temp;
}, this)}
这篇关于反应:遍历对象,查找数组,并显示数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文