javascript - 如何显示空购物车?
问题描述
我有一些(相当草率的)代码,我一直在为购物车工作。但我有一个问题,每当购物车为空时,页面将无法加载。我这里有代码。我能做些什么来解决这个问题?我正在考虑制作一个 EmptyCart 常量并在没有数据时激活它?但我不确定。这是代码。谢谢
import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux';
import {
removeCartItem,
onSuccessBuy
} from '../../../_actions/user_actions';
import UserCardBlock from './Sections/UserCardBlock';
import { Result, Empty, Button } from 'antd';
import Paypal from '../../utils/Paypal';
function CartPage(props) {
const dispatch = useDispatch();
console.log(props)
const [Total, setTotal] = useState(props.location.state.data.price)
const [ShowTotal, setShowTotal] = useState(true)
const [ShowSuccess, setShowSuccess] = useState(false)
const removeFromCart = (productId) => {
dispatch(removeCartItem(productId))
}
const transactionSuccess = (data) => {
dispatch(onSuccessBuy({
cartDetail: props.user.cartDetail,
paymentData: data
}))
.then(response => {
setShowSuccess(true)
setShowTotal(false)
}
)
}
const transactionError = () => {
console.log('Paypal error')
}
const transactionCanceled = () => {
console.log('Transaction canceled')
}
const propductList = (data) =>{
console.log(data)
setTotal(data)
}
return (
<div style={{ width: '85%', margin: '3rem auto' }}>
<h1>My Cart</h1>
<div>
<UserCardBlock
productData={props.location.state.data}
removeItem={removeFromCart}
productList = {data=>propductList(data)}
>
</UserCardBlock>
{ShowTotal ? (
<div style={{ marginTop: "3rem" }}>
<h2>Total amount: ${Total * 15} </h2>
</div>
) : ShowSuccess ? (
<Result status="success" title="Successfully Purchased Items" />
) : (
<div
style={{
width: "100%",
display: "flex",
flexDirection: "column",
justifyContent: "center",
}}
>
<br />
<Empty description={false} />
<p>No Items In The Cart</p>
</div>
)}
</div>
{/* Paypal Button */}
{ShowTotal &&
<Paypal
toPay={Total}
onSuccess={transactionSuccess}
transactionError={transactionError}
transactionCanceled={transactionCanceled}
/>
}
</div>
)
}
export default CartPage
解决方案
在尝试渲染 UserCardBlock 组件之前,您可以尝试添加三元检查以查看是否有道具数据。
{props.location.state.data &&
<UserCardBlock
productData={props.location.state.data}
removeItem={removeFromCart}
productList={data => propductList(data)}
/>
}
推荐阅读
- oracle - 获取 Oracle 表 ddl 但没有来自当前模式的额外详细信息的问题
- python - 使用 numpy 逐行查找唯一值的计数
- python - 如何在反应 webapp 中使用带有 TFIdVectorizer 的模型
- apache-kafka-streams - 如何使用 EmbeddedKafkaBroker 为主题创建多个分区?
- angular - Angular 类没有实现继承的抽象成员
- python - 如何在 docker 中仅发送通知请求
- python - 显示第一年并每年递增
- java - 在更新表之前使用Java检查确定mySQL表中是否有数据
- html - 如何使页面上的像素显示为整数?(铬合金)
- asp.net-core - 用户身份角色