我想重用我在 React-router-dom 中制作的菜单,但这次是在 nextjs 中。目标是当我单击菜单内的链接时,将菜单的状态更改为“false”,并将 menuName 更改为“menu”。
我使用 useEffect 函数来监听历史记录:
//use effect for page changes
useEffect(() => {
//listen for page changes
history.listen(() => {
setState({ clicked: false, menuName: "Menu" })
})
})
Run Code Online (Sandbox Code Playgroud)
并用 withRouter 包装我的组件:
import { withRouter } from 'next/router'
[...]
export default withRouter(Header);
Run Code Online (Sandbox Code Playgroud)
不幸的是,它打印:
TypeError: Cannot read property 'listen' of undefined
Run Code Online (Sandbox Code Playgroud)
我应该更好地使用“useRouter”来解决这个问题吗?如何?
谢谢 ;)
我不明白为什么当我刷新 nextjs 应用程序中的页面时,我总是回到索引页面。\n我有一个电子商务 SPA,其中包含 index.js 中的目录页面,并且产品通过动态显示[名称].js 页面。如果我通过浏览器刷新或后退按钮进行导航,路由就会变得一团糟。我想我错过了 nextjs 的一些良好实践。
\n索引.js
\nimport Head from "next/head";\nimport Catalogue from "../../components/Catalogue";\nimport { getProducts } from "../../utils/api";\n\nconst HomePage = ({ products }) => {\n return (\n <div>\n <Head>\n <title>Catalogue</title>\n <meta\n name="description"\n content="Classe moyenne \xc3\xa9ditions publie des livres et multiples d'artistes, \xc3\xa9mergeants ou reconnus, en France et \xc3\xa0 l'international."\n />\n <meta\n name="keywords"\n content="Edition d'artiste, Livres, prints, multiples, art books, librairie, concept store, Bookshop, Bookstore"\n />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n </Head>\n <Catalogue products={products} />\n …Run Code Online (Sandbox Code Playgroud)