首页 > 解决方案 > 如何在列表中显示本地存储项目?

问题描述

我是新来的反应,当涉及到这个时我一直被困住(dissapoinitng ik)。我正在处理结帐页面,我想显示用户从购物车中购买的商品的摘要。所述项目保存在本地存储中。当我控制台记录此信息时,它会显示出来。但我坚持如何在列表中显示这些结果。我会提供我的代码,但它很不稳定,所以请不要判断

评论.js

import React from "react";
import { Typography, List, ListItem, ListItemText } from "@material-ui/core";
import CartItems from "../Cart/CartItems";
import Product from "../Products/Product/Product";
import CartLayout from "../Cart/CartLayout";

const Review = ({ items }) => {

  console.log(localStorage.getItem("shoppingCart"));
  return (

    <div>
      <Typography variant="h6" gutterBottom>
        {" "}
        Order Summary
      </Typography>
        {items.map((item) => (
            <ListItem style={{ padding: '10px 0' }} key={item.VinylID}>
                item={item}
            </ListItem>
          ))}
    </div>
  );
};

export default Review;

PaymentForm.js

import React from "react";
import { Typography, Button, Divider } from "@material-ui/core";
// import { Element  } from '@stripe/react-stripe-js '
import { loadStripe } from "@stripe/stripe-js";
import Review from "./Review";

class PaymentForm extends React.Component {
  constructor(props) {
    super(props);
    let shoppingCart = JSON.parse(localStorage.getItem("shoppingCart"));
    this.state = {
       items: [] 
    };
  }
  render() {
    return (
      <div>
        <Review items={this.state.items} />
      </div>
    );
  }
}

export default PaymentForm;

我会回答有关我的代码的任何问题,因为我知道它可能会有点模糊

提前谢谢你的帮助!

标签: reactjslocal-storage

解决方案


我们需要查看 内容的格式shoppingCart,但您肯定想在您的项目列表中使用它,不是吗?

class PaymentForm extends React.Component {
  render() {
    const shoppingCart = JSON.parse(localStorage.getItem("shoppingCart"));
    return (
      <div>
        <Review items={shoppingCart} />
      </div>
    );
  }
}

更好的问题可能是:您的购物车如何改变,以及此列表是否需要重新渲染。但这似乎是一个很好的第一步。


推荐阅读