最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React - Map through array of objects - Stack Overflow

programmeradmin4浏览0评论

I'm able to map data when just using an object, but when using an array it doesn't some to work.

No errors in mand line just nothing outputted.

Help appreciated.

Thanks

import React from 'react';
import ReactDOM from 'react-dom';

class JoeApp extends React.Component {
    render() {
        var data = [
            {
                name: "Joe",
                age: 27
            },
            {
                name: "John",
                age: 27
            },
            {
                name: "Bill",
                age: 25
            }
        ];

        return (
            <Data data={data} />
        );
    }
}

class Data extends React.Component {
    render() {
        return (
            <div>{this.props.data.name.map((info) => info.name})}</div>
        );
    }
}

ReactDOM.render(<JoeApp />, document.body);

I'm able to map data when just using an object, but when using an array it doesn't some to work.

No errors in mand line just nothing outputted.

Help appreciated.

Thanks

import React from 'react';
import ReactDOM from 'react-dom';

class JoeApp extends React.Component {
    render() {
        var data = [
            {
                name: "Joe",
                age: 27
            },
            {
                name: "John",
                age: 27
            },
            {
                name: "Bill",
                age: 25
            }
        ];

        return (
            <Data data={data} />
        );
    }
}

class Data extends React.Component {
    render() {
        return (
            <div>{this.props.data.name.map((info) => info.name})}</div>
        );
    }
}

ReactDOM.render(<JoeApp />, document.body);
Share Improve this question asked Feb 11, 2017 at 23:59 Joe ConsterdineJoe Consterdine 1,0532 gold badges20 silver badges41 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You need to use the .map() function on the array itself, which would be this.props.data:

<div>{this.props.data.map((elem) => elem.name})}</div>

This will convert the array of objects:

var data = [
        {
            name: "Joe",
            age: 27
        },
        {
            name: "John",
            age: 27
        },
        {
            name: "Bill",
            age: 25
        }
    ];

To an array of name strings:

var data = ["Joe", "John", "Bill"];
发布评论

评论列表(0)

  1. 暂无评论