简体   繁体   English

Next.js 切换页面后变量重置

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

Im trying to simply have a shared variable between my pages in my Next.Js application.. My _app.js below contains the following..我试图在我的 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

I have two pages... Both are the same except one is called index.js and exports Home, the other is called about.js and exports About...我有两个页面...除了一个名为 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

When I tap the button the variable on my page changes to 1, however when I switch pages the variable goes back to 0. I also receive no errors of any sort.当我点击按钮时,我页面上的变量变为 1,但是当我切换页面时,变量又回到 0。我也没有收到任何类型的错误。 All feedback is greatly appreciated.非常感谢所有反馈。 Thanks for your time.谢谢你的时间。

The variable goes back to 0 because you are using a tags wich "reloads" the page To navigate you should use the Link component that is built in next.该变量返回到 0,因为您使用a标签 要导航,您应该使用接下来内置的Link组件。

This Link component prevents the default behavior of reload the page and you can keep your state while navigate on the pageLink组件可防止重新加载页面的默认行为,您可以在页面上导航时保留您的 state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM