我試圖在我的 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 和 export Home 之外,兩個都是一樣的,另一個叫做 about.js 和 export 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。我也沒有收到任何錯誤。非常感謝所有反饋!謝謝你的時間。
uj5u.com熱心網友回復:
該變數回傳 0,因為您使用的是a“重新加載”頁面的標簽。要導航,您應該使用Link下一個內置的組件。
該Link組件防止重新加載頁面的默認行為,您可以在頁面上導航時保持狀態
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/497971.html
標籤:javascript 节点.js 反应 下一个.js
下一篇:編輯源檔案中的主頁文本
