簡體   English   中英

Next.js 切換頁面后變量重置

[英]Next.js Variables reset after i switch pages

我試圖在我的 Next.Js 應用程序中的頁面之間簡單地共享一個變量。我下面的 _app.js 包含以下內容。


import { useState } from 'react';

const CustomApp = ({ Component, pageProps }) => {

  // Variables
  const [testVariable, setTestVariable] = useState(0)

  // globalFunctions
  const setTestVariable = (newValue) => setLocalVariable(newValue);


  return (
    <Component 
      {...pageProps}
      // Export Variables
      testVariable={testVariable}
      // Export Functions
      setTestVariable={setTestVariable}

    />
  );
}

export default CustomApp

我有兩個頁面...除了一個名為 index.js 並導出 Home,另一個名為 about.js 並導出 About 之外,它們都是相同的...

import { useState, useEffect } from 'react'
import 'bulma/css/bulma.css'
import styles from '../styles/Home.module.css'

const Home = ({ testVariable, setTestVariable, }) => {

 
  useEffect(() => {

  })

  
  return (
    <div id={styles.outerDiv}>
      <Head>
        <title>My Next.Js Page</title>
        <meta name="description" content="A Next.js application" />
      </Head>

      <div id={styles.navBar}>
        <a href="/" id={styles.navLink}>
          <h3>Home</h3>
        </a>
        <a href="/about.js" id={styles.navLink}>
          <h3>About</h3>
        </a>
      </div>

      <div id={styles.content} className="content">
        <br/>
        <h2>Test Variable: {testVariable}</h2>

        <button id={styles.incrementButton} onClick={setTestVariable(1)}>Set Test Variable to 1</button>

      </div>

    </div>
  )
}

export default Home

當我點擊按鈕時,我頁面上的變量變為 1,但是當我切換頁面時,變量又回到 0。我也沒有收到任何類型的錯誤。 非常感謝所有反饋。 謝謝你的時間。

該變量返回到 0,因為您使用a標簽 要導航,您應該使用接下來內置的Link組件。

Link組件可防止重新加載頁面的默認行為,您可以在頁面上導航時保留您的 state

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM