[英]How to conditionally render a button / Link Next.js Component with TypeScript
[英]I want to render the page on Next.js conditionally
我的 -app.js 上有以下代码:
import { useState, useEffect } from "react";
import PropTypes from "prop-types";
...
export default function MyApp(props) {
const { Component, pageProps } = props;
const [cartItems, setCartItems] = useState([]);
//this prop will be passed to all the pages
const passedProps = {
...pageProps,
cartItems: cartItems,
setCartItems: setCartItems,
};
...
//on App load do the following:
useEffect(() => {
...
//get cart items from localstorage if exist,else set to empty array;
const savedCartItems = localStorage.getItem("cartItems"),
cartItems = JSON.parse(savedCartItems) || [];
setCartItems(cartItems);
}, []);
return (
...
<Component {...passedProps} />
...
</>
);
}
MyApp.propTypes = {
Component: PropTypes.elementType.isRequired,
pageProps: PropTypes.object.isRequired,
};
以下是 checkout.js 上的代码
import { useEffect, useState } from "react";
import PropTypes from "prop-types";
import { useRouter } from "next/router";
...
export default function Checkout(props) {
router = useRouter(),
{ cartItems } = props;
...
// on checkout page load if cart is empty redirect to carts page
useEffect(() => {
!cartItems.length && router.push("/cart");
}, [cartItems, router]);
...
return (
...
}
Checkout.propTypes = {
cartItems: PropTypes.arrayOf(
PropTypes.shape({
title: PropTypes.string,
variations: PropTypes.objectOf(PropTypes.object),
qty: PropTypes.number,
price: PropTypes.number,
})
),
};
仅当购物车为空时,我才需要从结帐页面重定向到购物车页面,但即使购物车有商品,我每次都会被重定向。 我认为这是因为在初始页面加载时,项目仍未从本地存储加载到父应用程序组件并且仍未定义。 有什么解决办法吗??
您的问题是因为您使用长度为 0 的空数组初始化cartItems
,因此始终执行:
!cartItems.length && router.push("/cart");
相反,在没有值的情况下对其进行初始化:
const [cartItems, setCartItems] = useState();
并将 useEffect 更改为:
// on page Load,if cart is empty redirect to carts page
useEffect(() => {
if (Array.isArray(cartItems) && cartItems.length === 0) {
router.push("/cart");
}
}, [cartItems, router]);
这样,重定向只会在以下情况下执行:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.