从axios API检索的javascript中的JSON中的冲浪对象数组

时间:2018-09-18 10:03:21

标签: javascript json reactjs parsing axios

我在React中调用Axios例如API,我只想在数组中呈现特定字段,例如在输出中仅显示第一人称公司名称。 例如“ person [0] .cpmpany.name”,我期望有“ Romaguera-Crona”,但出现错误。

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "address": {
      "street": "Kulas Light",
      "zipcode": "92998-3874",
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "address": {
      "street": "Victor Plains",
      "zipcode": "92998-3874",
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
    }
  },...]

我的反应成分是:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


export default class PersonList extends React.Component {
    state = {
        persons: []
    };

    componentDidMount() {
        axios.get(`https://jsonplaceholder.typicode.com/users`)
            .then(res => {
                const persons = res.data;
                // const persons2 = JSON.parse(persons);
                this.setState({ persons : persons});
            })
    }

    render() {
        return (
            <ul>
                { this.state.persons.map(person => <li>{person.phone}</li>)}
                { this.state.persons.map(person => <li>{person.address.street}</li>)}
              // { this.state.persons.map(person => <li>{person[0].cpmpany.name}</li>)} // here is the issue

            })
            </ul>
        )
    }
}

我想从JSON文件呈现特定组件,或在5月JSON对象中的特定单元格上循环。例如仅渲染person.cpmpany.name

的for循环

1 个答案:

答案 0 :(得分:0)

{person[0].cpmpany.name}中有一个错字。另外,由于您已经在this.state.persons数组上进行映射,因此可以简单地使用{person.company.name}

请尝试将{person[0].cpmpany.name}替换为{person.company.name}