2016-11-17 27 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