如何在 React.js 中获取数组值
2016-11-17
22976
我想获取数组的更新值。当我执行 console.log 时,我仅获取数组的长度,而新值未显示在视图中。这里出了什么问题? js fiddle
react js
getInitialState: function() {
return {
owner: "Martin Schwatz",
friends: ["Pietro", "Mike", "Shawn", "Bilbo"],
}
},
updateFriends: function(friend) {
var a = this.state.friends.push(friend);
console.log(a);
this.setState({
friends: a,
});
},
2个回答
看一下这个
var Hello = React.createClass({
getInitialState: function() {
return {
owner: "Martin Schwatz",
friends: ["Pietro", "Mike", "Shawn", "Bilbo"],
}
},
updateFriends: function(friend) {
var newFriends = this.state.friends.concat(friend)
this.setState({
friends: newFriends,
});
},
click: function(){
this.updateFriends('VuVu')
},
render: function(){
var listOfFriends = this.state.friends.map(function(item,i){
return <li key={i}>{item}</li>
}.bind(this))
return <div>
<button onClick={this.click}>Add VuVu</button>
<hr/>
{listOfFriends}
</div>
}
});
ReactDOM.render(
<Hello />,
document.getElementById('container')
);
它应该对你有用<
fiddle
>
The Reason
2016-11-17
push
返回变异数组的新长度。因此,在当前代码中,
a
不会是数组
本身
。
请尝试以下方法:
updateFriends: function(friend) {
const newFriends = [ ...this.state.friends, friend ];
this.setState({
friends: newFriends,
});
},
Davin Tryon
2016-11-17