【发布时间】:2021-06-04 16:48:37
【问题描述】:
我的 -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,
})
),
};
仅当购物车为空时,我才需要从结帐页面重定向到购物车页面,但即使购物车中有商品,我每次都会被重定向。我认为这是因为在初始页面加载时,项目仍未从本地存储加载到父应用程序组件并且仍未定义。有什么解决办法吗??
【问题讨论】:
-
那么您是否希望重定向仅在页面加载时发生?如果有人稍后在页面上向卡片添加项目,它不应该重定向吗?
-
结帐是一个单独的页面。如果购物车中没有商品,结帐应立即重定向。假设有人在 url 中键入以下地址:localhost/checkout。现在如果购物车是空的,他应该被重定向到购物车页面。你明白我的意思了吗??
-
你的路由器是否响应路由器 dom?
-
没有它的“下一个/路由器”。
-
它不是路由器问题,它的发生是因为使用效果,由于 next.js 中的 SSR,我必须在 useEffect 中重定向。问题是一开始没有从本地存储中加载项目并且购物车是空的。
标签: javascript reactjs next.js use-effect