我最近开始在一个新项目上使用Next.JS,它工作正常,但是当我单击错误的链接后引发404错误时,我不知道如何在客户端保持我的布局状态为活动状态。
由于Adam's Wathan article,我可以在不同页面之间共享我的状态:
在首页上
在“关于”页面上
但是,如果我单击“错误”,它将呈现_error.tsx,而不会保留我在输入中编写的数据。
尽管我提供了相同的布局,但该页面似乎在服务器端呈现了整个应用程序树。无论如何,是否像常规页面一样预取此页面,并且避免在不使用Redux之类的解决方案的情况下丢失某些信息?我注意到它非常熟悉,在这种情况下似乎有点过多。
这是我的代码: pages / _error.tsx
import { getLayout } from "../components/layout/mainLayout"
import { withTranslation } from "../i18n";
import { FlexDirectionProperty } from "csstype";
const imgStyle = {
maxWidth: "100%",
maxHeight: "100%"
};
const figureStyle = {
height: "80vh",
display: "flex",
justifyContent: "center",
alignItems: "center",
flexDirection: "column" as FlexDirectionProperty
};
const CustomError: any = ({ status, t }: any) => (
<>
<figure style={figureStyle}>
<figcaption>
<h1>Statut:{t('WELCOME')}</h1>
</figcaption>
<img
alt="Showing a properly cat according the status code"
src={`https://http.cat/${status}`}
style={imgStyle}
/>
</figure>
</>
)
CustomError.getLayout = getLayout;
CustomError.getInitialProps = async ({ res, err }: any) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : null
return {
statusCode: statusCode,
namespacesRequired: ["common"]
}
};
export default withTranslation('common')(CustomError)
components / layout / header.tsx
import Link from "next/link";
import Navbar from "react-bootstrap/Navbar";
import Nav from "react-bootstrap/Nav";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import { withTranslation, i18n } from "../../i18n";
import { capitalize } from "../../helpers/utils";
import Modal from "react-bootstrap/Modal";
import { useState } from "react";
const loadStamp = +new Date();
const Header: any = ({ t }: any) => {
const [show, setShow] = useState(false);
const [active, setActive] = useState("home");
return (
<>
<Navbar fixed="top" bg="light">
<Nav className="mr-auto" activeKey={active}>
<Nav.Item>
<Link href="/">
<Navbar.Brand onClick={() => setActive("home")} href="/">Random Project</Navbar.Brand>
</Link>
</Nav.Item>
...
</Nav>
</Navbar>
</>);
};
export default withTranslation("common")(Header);
components / layout / mainLayout.tsx
import Header from "./header";
import "bootstrap/dist/css/bootstrap.min.css";
import "../../public/stylesheets/style.scss";
type LayoutProps = {
title?: string;
children: any;
};
const Layout: React.FunctionComponent<LayoutProps> = ({ children }) => (
<>
<Header />
<main role="main" className="main">
{children}
</main>
</>
);
export const getLayout: any = (page: any) => <Layout>{page}</Layout>
export default Layout
还有我的_app.tsx
import React from 'react'
import App from 'next/app'
import { appWithTranslation } from '../i18n'
class MyApp extends App<any> {
render() {
const { Component, pageProps } = this.props
const getLayout = Component.getLayout || ((page: any) => page)
return (
<>
{getLayout(
<Component {...pageProps}></Component>
)}
</>
)
}
}
export default appWithTranslation(MyApp)