我想迭代这个json字符串并将值输入到react组件中:{"users":[{"name":"jkhhjjh","url":"/users/240/individual_show"},{"name":"bob","url":"/users/241/individual_show"}]}
我当前可以从json索引中的第一个或第二个对象创建一个组件,但我无法迭代整个字符串。我的react-jsx代码如下:
enter code here
var FriendInfo = React.createClass({
getInitialState: function() {
return {
url: '',
name: ''
};
},
componentDidMount: function() {
$.get(this.props.source, function(user) {
var users= user["users"][0];
if (this.isMounted()) {
this.setState({url: users.url,
url: users.url,
name: users.name
});
}
}.bind(this));
},
render: function() {
return (
<div className="friendInfo">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/92/SRC-TV.svg/140px-SRC-TV.svg.png"></img>
<a href={this.state.url}>{this.state.name}</a>
</div>
);
}
});
var RequestLinks= React.createClass({
render: function() {
return (
<div className="requestLinks" style={{float:"right"}}>
<a href="accept.com">accept</a>
<a href="deny.com">deny</a>
</div>
);
}
});
var FriendBox = React.createClass({
render: function() {
return (
<div className="friendBox">
<FriendInfo source="/individual_relationships/show"/>
<RequestLinks />
</div>
);
}
});
React.render(<FriendBox />, document.getElementById('test'));`enter code here`
在行var users= user["users"][0]
之后,我能够将数据插入到组件的一次迭代中。我想创建一个循环,迭代user["users"][0]
和user["users"][1]
以在页面上创建两个组件。我该怎么做呢?
答案 0 :(得分:0)
你需要使用map函数来返回单个元素的数组。
var FriendInfo = React.createClass({
getInitialState: function () {
return {
users: []
};
},
componentDidMount: function () {
$.get(this.props.source, function (user) {
var users = user["users"];
if (this.isMounted()) {
this.setState({users: users});
}
}.bind(this));
},
render: function () {
return (
<div>
{
this.state.users.map(function (user) {
return <div className="friendInfo">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/92/SRC-TV.svg/140px-SRC-TV.svg.png"></img>
<a href={user.url}>{user.name}</a>
</div>
})
}
</div>
);
}
});
var RequestLinks = React.createClass({
render: function () {
return (
<div className="requestLinks" style={{float: "right"}}>
<a href="accept.com">accept</a>
<a href="deny.com">deny</a>
</div>
);
}
});
var FriendBox = React.createClass({
render: function () {
return (
<div className="friendBox">
<FriendInfo source="/individual_relationships/show"/>
<RequestLinks />
</div>
);
}
});
React.render(<FriendBox />, document.getElementById('test'));