[英]I want the music to continue playing as I switch pages(tabs). 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.