首页 > 解决方案 > 在带有状态和道具的列表中显示 JSON 对象

问题描述

我正在尝试获取包含有关多个对象的信息的 json 文件,但我似乎无法正确处理。我对做出反应还很陌生,所以我有可能把事情和这个、状态和道具或其他东西混为一谈。

我已经成功地从控制台中的 json 接收到对象列表,但我无法在我的 return 语句中显示它们。

感谢您的帮助!

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

class PlayerFeed extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            'playerList': []
        };
    }
    componentDidMount() {
        this.getPlayers();
    }

    getPlayers() {
        fetch('http://link.to/json/players/')
            .then(results => results.json())
            .then(results => console.log(results))
            .then(results => this.setState({'playerList': results}));
    }
    render() {
        return (
                <ul>
                    {this.props.state.map(function(players, index) {
                    return (
                        <div key={index}>
                                <h1>{this.props.age}</h1>
                                <p>{this.props.height}</p>
                        </div>
                    )
                }

                )}
            </ul>
        );
    }
}

ReactDOM.render(
    <PlayerFeed />,
    document.getElementById('root')
);

标签: jsonreactjs

解决方案


道具和状态本质上是两个不同的实体。

  1. Props 是提供给你的组件的数据
  2. 状态是组件中定义的数据

查看您的代码,因为它是一个单级组件,所以没有提供任何道具。您应该将代码更改为 -

{this.state.playerList.map(function(players, index) {
                return (
                    <div key={index}>
                            <h1>{players.age}</h1>
                            <p>{players.height}</p>
                    </div>
                )})}

假设您的playerList对象具有ageheight属性。

希望这能解决:)


推荐阅读