React:迭代对象,查找数组,并显示数组项

时间:2017-05-18 00:03:39

标签: arrays reactjs asp.net-mvc-4

我试图通过对#34; / Home / NewsNotes"" / Home / NewsNotes"

的axios调用来回溯一个正在返回的对象。

Axios的回应 enter image description here

我能够在屏幕上显示属性名称,但我在访问" NewsNotes"时遇到问题。阵列。

enter image description here

这是我的组件代码。

enter image description here

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')
);

2 个答案:

答案 0 :(得分:0)

您无法使用键渲染元素数组。而是映射数组并像这样打印它们。

renderReleaseNotes() {
  return _.map(this.state.releaseNotes, releaseNote => {
    return (
      <p>releaseNote.title</p>

    );
  });
}

希望这会有所帮助。快乐的编码!

答案 1 :(得分:0)

我假设您使用axios从URL检索的对象将如下所示:

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
};

接下来,你可以注入&#34;这个&#34;到map方法如下,检查任何子数组,然后将每个JSX块推入临时数组,以便稍后返回:

{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)}