使用state和props在列表中显示JSON对象

问题描述 投票:0回答:2

我试图获取一个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')
);
json reactjs
2个回答
0
投票

道具和州基本上是两个不同的实体。

  1. 道具是提供给组件的数据
  2. State是组件中定义的数据

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

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

假设你的playerList对象有ageheight属性。

希望这解决:)


0
投票

我认为你应该在状态而不是道具中循环播放列表。道具是从父组件获得的。

render() {
    return (
            <ul>
                {
                for(var player of  this.state.playerList) {
                  return (
                    <div key={player.index}>
                            <h1>{player.age}</h1>
                            <p>{player.height}</p>
                    </div>)
                }
            }
        </ul>
    );
}

此外,您可以在chrome中安装react develop插件,以查看状态和道具中的值。

© www.soinside.com 2019 - 2024. All rights reserved.