所以我有一个非常简单的组件:
const in_cart = (
<CartItems>
<ItemInCart>
<InCartFont>{ITEM NAME}</InCartFont>
<CartRemove>
<CartX>x</CartX>
<br></br>
remove
</CartRemove>
</ItemInCart>
</CartItems>)
我想知道是否有这样一种方式使用它:
function App() {
let items_in = JSON.parse(localStorage.getItem('products')).length;
for (i = 0; i === items_in; i++) {
return (
in_cart(i)
)
}
};
ReactDOM.render( <App />, document.getElementById('root'));
console.log(JSON.parse(localStorage.getItem('products')))提供以下内容:
(10) [{…}, {…}, {…}, ... , {…}]
0: {itemName: ""}
1: {itemName: ""}
2: {itemName: ""}
3: {itemName: ""}
4: {itemName: "Blekk BROTHER LC1280XLC blå"}
5: {itemName: "Blekk BROTHER LC1280XLM rød"}
6: {itemName: "Blekk BROTHER LC1280XLY gul"}
7: {itemName: "Blekk BROTHER HCBK 30K sort"}
8: {itemName: ""}
9: {itemName: ""}
10: {itemName: ""}
我想使用从本地存储中读取的{ITEM NAME}渲染我的组件,我猜是这样的:
let {ITEM NAME} = JSON.parse(localStorage.getItem('products'))[i]
答案 0 :(得分:1)
您快到了:
function CartItem(props) {
return (
<ItemInCart>
<InCartFont>{props.item.itemName}</InCartFont>
<CartRemove>
<CartX>x</CartX>
<br></br>
remove
</CartRemove>
</ItemInCart>
);
}
function App() {
// don't need the length here, let's just get the items
let items = JSON.parse(localStorage.getItem('products'));
// since we have an array, we can map over every item
return (
<CartItems>
{items.map((item, index) => {
return <CartItem item={item} key={index} />
})}
</CartItems>
);
};
ReactDOM.render( <App />, document.getElementById('root'));
我假设您的JSX中的所有其他组件都是真实的组件,并且我不会编辑其他任何内容。
答案 1 :(得分:0)
这是一个沙盒示例:https://codesandbox.io/s/dreamy-edison-nep4e
注释在代码中,但快速注释是:
Array.prototype.map
是在React中显示项目列表的最便捷方法props
!