根据Cookie多次渲染组件

时间:2019-06-12 11:07:45

标签: javascript reactjs cookies

所以我试图创建一个购物车来显示保存在cookie中的物品。这是我所拥有的:

function safe_item(name) {
document.cookie += 'item name: ' + name + '?';
}

此函数由onClick事件调用,但是我想这没关系,因为我的console.log(document.cookie.split('?'))正确返回了数据:

0: "item name: Blekk BROTHER LC1000 Value Pack"
1: "item name: Blekk BROTHER LC1000 Value Pack"
2: "item name: Blekk BROTHER LC1000Y gul"
3: "item name: Blekk BROTHER LC1100 Value sort+CMY (4)"
4: "item name: Blekk BROTHER LC1000 Value Pack"
5: "item name: Blekk BROTHER LC1280XLC blå"
6: "item name: Blekk BROTHER LC1280XLM rød"
7: "item name: Blekk BROTHER LC1280XLC blå"
8: "item name: Blekk BROTHER LC1280XLC blå"
9: "item name: Blekk BROTHER LC1280XLM rød"

现在,我想使用Cookie中的项目名称来呈现组件:

let cookie = document.cookie.split('?');

function InCart() {
for (let i = 0; i < cookie.length; i++) {
return (
  <ItemInCart>
      <InCartFont>{cookie[i].item name}</InCartFont>
      <CartRemove>
        <CartX>x</CartX>
        <br></br>
        remove
      </CartRemove>
    </ItemInCart>
  )
  }
  }

  export default InCart;

当我运行我的应用程序时,它会按预期呈现,但只有一次且为空。虽然我需要循环执行此过程,然后从Cookie中插入商品名称。

console.log(cookie)输出良好,我缺少什么?

1 个答案:

答案 0 :(得分:1)

您不能多次return。请将单个returnmap()一起使用:

function InCart() {

return (
<div>
{ cookies.map( cookie =>
  (<ItemInCart>
      <InCartFont>{cookie.item name}</InCartFont>
      <CartRemove>
        <CartX>x</CartX>
        <br></br>
        remove
      </CartRemove>
    </ItemInCart>)
</div>
  ))
  }
  }

  export default InCart;