将props数组传递给子组件

时间:2018-12-09 00:55:46

标签: javascript reactjs

我正尝试将对象的数组从父对象传递给子组件作为道具,然后对其进行映射并在子组件中显示它。当我尝试映射它时,什么都没有发生,当我console.log它时,它显示了我的对象数组。有什么区别,这里发生了什么?

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

1 个答案:

答案 0 :(得分:1)

这是因为您要在数组中存储数组,然后尝试访问数组中的对象属性。

更改此行:

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}相同

相关问题