Lets say there are 2 components Main and Card, Card is child of Main in React.js. Card will pass in an string value to Main. Thus state in Main for the Card would update.
var Card= React.createClass({
...
this.props.updateName(loginVal.value); //pass in a 'string' to updateName()
...
});
var Main = React.createClass({
getInitialState: function() {
return {
names: []
};
},
updateName: function (loginVal) {
this.setState({
names: this.state.names.concat(loginVal) // I don't understand why using 'concat' works but not 'push'.
});
},
render: function(){
var cardArr = this.state.names.map(function(item){
return ( <Card login={item} /> );
});
return (
<div>
<Form updateName={this.updateName} />
{cardArr}
</div>
);
}
});
My question is why this.state.names.concat(loginVal)
works when this.state.names
is an empty array
and loginVal
is a string
. [].concat('string')
just don't make sense to me.
push
adds the provided element(s) and returns the new length of the array, sothis.state.names
would be a number.concat
adds the provided element(s) to a new array and returns it, sothis.state.names
would be an array with the new name added.