Next JS - 仅在第一页加载时基于查询参数显示模态

Next JS - Show modal based on query param just on first page load

我想根据查询参数的存在在第一个页面加载时显示模态,而不是在用户刷新页面时再次显示它,我应该如何处理?(查询参数是可变的) 我已经通过 set cookie 尝试过,但效果不佳。

据我了解,您需要以下内容:

  1. 根据查询字符串打开模式。
  2. 如果已打开,则不打开模式。

假设 url 是 www.mysite.com/payment?paymentStatus=success&paymentId=111

import { withRouter, Link } from 'react-router';
import queryString from 'query-string';
import Cookies from 'universal-cookie';// Haven't tried it but probably works from the repo
import Modal from 'some-modal-library';

const cookies = new Cookies();

const PaymentHandler = (props) => {
    const {paymentStatus, paymentId} = queryString.parse(props.location.search) || {};
    console.log(params); // {paymentStatus: 'success', paymentId: '111'}
    const openModal = paymentStatus && paymentStatus === 'success' ? true : false;

    if (openModal) {
        // Check if stored in cookies based on the paymentId previously
        const paymentStatusFromCookie = cookies.get(paymentId);
        if (paymentStatusFromCookie && paymentStatusFromCookie === 'success') {
            // This means we've already set it. Just return null or react fragment
            // This will not render the modal on the DOM
            return <></>;
        }

        // Else set the cookie and allow the modal render
        cookies.set(paymentId, paymentStatus, { path: '/' });
    }

    return (
        <Modal
            open={openModal}
        >
            <h2>Your payment was successful</h2>
            {/*Reroute to another page once close to even avoid refresh in the first place*/}
            <Link to="/" />Close</Link>
        </Modal>
    )
}

export default withRouter(PaymentHandler);