ReactJS:this.props.data.map不是函数

时间:2016-02-15 21:56:36

标签: javascript jquery json reactjs

我正在尝试从.json文件中获取数据并通过视图显示结果。以下是scoreboard.json文件。

{
"subject":"scoreboard",
"copyright":"Copyright 2015",
"data":
   "games":{
     "next_day_date":"2015-07-22",
     "modified_date":"2015-08-04T07:34:50Z",
     "month":"07",
     "year":"2015",
     "game":[
        {
           "game_type":"R",
           "double_header_sw":"N",
           "location":"Some City, State",
        }, 
        {
           "game_type":"R",
           "double_header_sw":"N",
           "location":"Another City, Another State"
        }
     ]
   }

我只想要"数据"字段而不是"主题"或"版权"字段,我可以通过下面的ajax请求这样做。



	getInitialState: function() {
		return {data: []};
	},
	componentDidMount: function() {
		$.ajax({
		  url: this.props.url,
		  dataType: 'json',
		  cache: false,
		  success: function(data) {
		  	console.log(data.data);
		    this.setState({data: data.data});
		  }.bind(this),
		  error: function(xhr, status, err) {
		    console.error(this.props.url, status, err.toString());
		  }.bind(this)
		});
	},




我将状态传递给接收文件但是,当我尝试调用它时,我收到TypeError: this.props.data.map is not a function



	render: function() {
		var gameDate = this.props.data.map(function(data) {
			return (
				<h1>{data.modified_date} </h1>
			);
		});
&#13;
&#13;
&#13;

我希望能够获得&#34;数据&#34;中的所有信息。 scoreboard.json的字段最终(即data.games.game []数组)。 .map函数似乎也不适用于此。

我如何获得&#34;数据&#34; .map函数中的字段(更具体地说是modified_date)?

编辑:我可以通过调用data.games.modified_date来记录modified_date但是,在尝试设置数据状态时:this.state.data = data.games.game我收到一条新警告:Each child in an array or iterator should have a unique "key" prop. Check the render method of "GameDate"

1 个答案:

答案 0 :(得分:4)

正如azium指出的那样,我的数据是对象,而不是像我的结果所期望的数组

获得#34;游戏&#34; #34;游戏中的阵列&#34;字段我将状态设置如下:

this.setState({data: data.data.games.game});

要获取其他字段,我只需创建一个新状态并通过prop传递它,即modified_date:

this.state.date = data.data.games.modified_date

警告:Each child in an array or iterator should have a unique "key" prop.是通过添加&#34;键&#34;来解决的。 .map方法中的属性:

render: function() {
    var gameDate = this.props.data.map(function(data) {
        return (
            <h1 key={data.location} >{data.location} </h1>
        );
    });