ReactJS不能使用map()显示对象属性

时间:2015-03-21 16:05:36

标签: reactjs reactjs.net

我的组件中的代码。我最终想要做的是构建一个选项,其中的选项是从

返回的朋友列表



/*** @jsx React.DOM */

var FriendSelect = React.createClass({
	getInitialState: function(){
		return {
			friends: []
		};
	},
	componentDidMount: function(){
		this.loadFriends();
	},
	loadFriends: function (){
		
		$.ajax({
	        async: true,
	        type: "GET",
	        url: "../../Messaging/_GetFriends",
	        success: function (data) {
	        	this.setState({ friends: data });
	        	console.log("data in ajax: ",data);
	        }.bind(this)
	    });
	    
	},
	handleSelections: function  (){
		console.log('selection changed');
	},
	render: function(){

	    console.log('this.state.friends', this.state.friends);

		return (
			<div>
				{this.state.friends.map(function(friend){
					<span>{friend.text}</span>
				})}
			</div>
		);
	}
});

React.render(<FriendSelect />, document.getElementById('friendSelection'));
&#13;
&#13;
&#13;

这是在ajax调用之后返回的json。

&#13;
&#13;
[{"id":"8qdzmV","text":"fernando roman","firstName":"first","lastName":"last","pictureName":"00000000-0000-0000-0000-000000000000","pictureExt":".jpg"},{"id":"8qdzmV","text":"Anthony Macias","firstName":"first2","lastName":"last2","pictureName":"00000000-0000-0000-0000-000000000000","pictureExt":".jpg"},{"id":"8qdzmV","text":"Carla Velasco ","firstName":"first3","lastName":"last3","pictureName":"011ab238-0b3a-44ff-aeda-02e6fbdcca56","pictureExt":".jpg"}]
&#13;
&#13;
&#13;

当组件被渲染时,我没有得到任何错误,问题是每个朋友的文本属性都没有被渲染。

1 个答案:

答案 0 :(得分:0)

return

中需要map
        <div>
            {this.state.friends.map(function(friend){
                return <span>{friend.text}</span>
            })}
        </div>

JSX没有输出的副作用 - 它只是评估一个可以返回的元素。

如果启用es6转换,则可以避免这种情况:

<div>{
    this.state.friends.map(friend => <span>{friend.text}</span>)
}</div>

您可以使用browserify / reactify并修改package.json:

来完成此操作
  "browserify": {
    "transform": [
      [
        "reactify",
        {
          "es6": true
        }
      ],
      "envify"
    ]
  },