我想获取数组的更新值。当我执行console.log时,我只获取数组的长度,并且新值不会显示在视图中。这有什么不对? js fiddle
反应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,
});
},
答案 0 :(得分:1)
push
返回变异数组的新长度。因此,在当前代码中,a
将不是数组本身。
请改为尝试:
updateFriends: function(friend) {
const newFriends = [ ...this.state.friends, friend ];
this.setState({
friends: newFriends,
});
},
答案 1 :(得分:1)
看一下这个
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')
);
它应该适合你&lt; fiddle
&gt;