Reputation: 962
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.
Upvotes: 0
Views: 4453
Reputation: 3149
[].concat(["string", "other string")
will push each value to an new empty array. You can also pass a simple string instead of an array because the method was overwritten to make it more flexible.
push("string")
do not work because it will return the new length of the array. But it will change the array instead of creating a new one.
you could use this:
this.state.names.push(value);
this.setState({
names: this.state.names
});
Upvotes: 1