2016-11-17 30 views
2

我想获取数组的更新值。当我做一个console.log我只得到数组的长度和新值不显示在视图中。这里有什么问题? js fiddle如何获取数组值js

反应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

@DavinTryon工作,但如何将一个反应开发商拿到数组中的新值? – vuvu

+0

'push'返回数组的长度。 –

回答

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') 
); 

它应该为你< fiddle>

+0

感谢您接受和改进! – vuvu

1

push返回突变阵列的新长度。所以,在目前的代码中,a将不会是本身的

试试这个:

updateFriends: function(friend) { 
    const newFriends = [ ...this.state.friends, friend ]; 
    this.setState({ 
    friends: newFriends, 
    }); 
}, 
+0

非常感谢你! – vuvu