Javascript 将道具数组传递给子组件
我试图将一组对象作为道具从父组件传递给子组件,然后在其上进行贴图并在子组件中显示。当我尝试映射它时,什么也没有发生,当我使用console.log时,它显示了我的对象数组。有什么区别,这里出了什么问题Javascript 将道具数组传递给子组件,javascript,reactjs,Javascript,Reactjs,我试图将一组对象作为道具从父组件传递给子组件,然后在其上进行贴图并在子组件中显示。当我尝试映射它时,什么也没有发生,当我使用console.log时,它显示了我的对象数组。有什么区别,这里出了什么问题 class ClothingBuyingOptions extends Component { state = { size: '', color: '', showShoppingBag: false, items: [] } addItemToBag
class ClothingBuyingOptions extends Component {
state = {
size: '',
color: '',
showShoppingBag: false,
items: []
}
addItemToBag = () => {
const { size, color } = this.state;
this.setState({
showShoppingBag: true,
items: [ ...this.state.items, [{ size: size, color: color }]]
});
}
render() {
return (
<div>
<button
onClick={this.addItemToBag}>
Add to Bag
</button>
<ShoppingBag items={this.state.items} />
</div>
);
}
}
class ShoppingBag extends Component {
render() {
const items = this.props.items.map((item, index) =>
<div
key={index}>
<p>{item.size}</p>
<p>{item.color}</p>
</div>
)
console.log(this.props.items)
return (
<div className="container">
{items}
</div>
);
}
}
class ClothingBuyingOptions扩展组件{
状态={
大小:“”,
颜色:'',
showShoppingBag:错误,
项目:[]
}
addItemToBag=()=>{
const{size,color}=this.state;
这是我的国家({
showShoppingBag:没错,
items:[…this.state.items,[{size:size,color:color}]]
});
}
render(){
返回(
添加到包中
);
}
}
类ShoppingBag扩展组件{
render(){
const items=this.props.items.map((项目,索引)=>
{item.size}
{item.color}
)
console.log(this.props.items)
返回(
{items}
);
}
}
这是因为您将数组存储在数组中,然后尝试访问数组上的对象属性
更改此行:
items: [ ...this.state.items, [{ size: size, color: color }]]
为此:
items: [ ...this.state.items, { size: size, color: color }]
使用代码构造状态的方式如下所示:
items: [
[ { size: '', color: ''} ],
[ { size: '', color: ''} ]
]
你希望它是这样的:
items: [
{ size: '', color: ''},
{ size: '', color: ''}
]
此外,由于对象键和值相同,因此可以将对象定义为
{size,color}
,这与{size:size,color:color}
项作为空数组启动相同。何时或如何调用addItemToBag()
?我有一个按钮,可以在单击时调用它<代码>添加到行李
项目为空。状态将被合并,无需使用…this.state.item调用状态。您需要设置要处于状态的项的状态。按钮在哪里?:)对不起,删掉很多,使它更简洁。把按钮加回去。不知道你的意思,如果我不使用扩展操作符调用它,我如何继续添加到数组中?谢谢,这很有用。