繁体   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