简体   繁体   English

对象文字值和React.js

[英]Object literal values and React.js

Lets say there are 2 components Main and Card, Card is child of Main in React.js. 可以说Main和Card有2个组成部分,Card是React.js中Main的子元素。 Card will pass in an string value to Main. 卡将一个字符串值传递给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 . 我的问题是,当this.state.names是一个empty arrayloginVal是一个string时,为什么this.state.names.concat(loginVal)起作用。 [].concat('string') just don't make sense to me. [].concat('string')对我来说毫无意义。

push adds the provided element(s) and returns the new length of the array, so this.state.names would be a number. push添加提供的元素并返回数组的新长度,因此this.state.names将是一个数字。

concat adds the provided element(s) to a new array and returns it, so this.state.names would be an array with the new name added. concat将提供的元素添加到新数组中并返回它,因此this.state.names将是添加了新名称的数组。

[].concat(["string", "other string") will push each value to an new empty array. [].concat(["string", "other string")将每个值推送到一个新的空数组。 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. push("string")不起作用,因为它将返回数组的新长度。 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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM