gpt4 book ai didi

javascript - 对象字面值和 React.js

转载 作者:行者123 更新时间:2023-12-02 16:02:29 26 4
gpt4 key购买 nike

假设有 2 个组件 Main 和 Card,Card 是 React.js 中 Main 的子组件。Card 将向 Main 传递一个字符串值。因此,卡的 Main 状态将会更新。

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

我的问题是为什么当 this.state.names 是一个空数组this.state.names.concat(loginVal) 起作用并且loginVal 是一个字符串[].concat('string') 对我来说没有意义。

最佳答案

push添加提供的元素并返回数组的新长度,因此 this.state.names 将是一个数字。

concat将提供的元素添加到新数组并返回它,因此 this.state.names 将是添加了新名称的数组。

关于javascript - 对象字面值和 React.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31065963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com