nextjs概述
前言:nextjs是昨天真正开始了解,之前都是打酱油,原来这个框架是react,路由,参数传递,页面复用,服务端渲染等做得很好。
next.js作为一款轻量级的应用框架,主要用于构建静态网站和后端渲染网站。
框架特点
使用后端渲染
自动进行代码分割(code splitting),以获得更快的网页加载速度
简洁的前端路由实现
使用webpack进行构建,支持模块热更新(Hot Module Replacement)
可与主流Node服务器进行对接(如express)
可自定义babel和webpack的配置
路由
使用nextjs之后,再也无需为配置路由而操心,只需要放到pages文件夹下面,nextjs就自动生成了路由,
只要按文件夹路径去访问即可,例如上图中的my-orders路径,我们可以直接访问http://localhost:3000/my-orders/,根本不用再路由上面花费精力
参数传递
页面之间难免会有参数传递
我们只需要将文件名[参数名]的方式命名即可,接收参数的时候直接const id = router.query.参数名;即可,十分优雅十分简洁。
页面复用
有时候,两个页面布局差不多,可能只有微小区别,这个时候我们可以加一个参数来区分下,比如加一个type参数:
在页面里面获取type类型,生成新的页面路径:
export function getStaticPaths(): GetStaticPathsResult { return { paths: [ { params: { type: "return-product", }, }, { params: { type: "report", }, }, ], fallback: false, }; }
上面这个例子就会生成两个页面的路由,一个是:http://localhost:3000/my-orders/select-resons/return-product,另一个是:http://localhost:3000/my-orders/select-resons/report,假如我们此处随便输入别的值,会报404
nextjs搭配scss
nextjs如果要用scss的话,需要把scss命名加.module.scss,否则会不识别,引用的时候必须:
import styles from "./BillingForm.module.scss";
<div className={classNames("mx-auto hidden md:block", styles.editButton)}>
<Link href={pathnames.editBillingDetails}>
<a>
<CustomButton primary rounded fullSize noMargin label="EDIT" />
</a>
</Link>
</div>
注意:这里不能直接import "./BillingForm.module.scss";,然后className的方式引用scss,会失败,这一点不知道为何要这么设计?好像是为了避免css命名污染问题。
程序入口
nextjs之后程序总入口是_app.tsx或_app.jsx,这个文件默认是没有的,只有你需要的时候你可以自己添加这个文件,比如我这个项目:
这个一般处理一些和redux或者react context相关的操作,比如此处:
import { ApolloProvider } from "@apollo/client";
import { AppProps } from "next/app";
import Head from "next/head";
import React from "react";
import ScrollControlProvider from "../components/shared/ScrollControlProvider";
import { SystemNotificationContainer } from "../components/shared/SystemNotifications";
import { useApollo } from "../lib/apolloClient";
import "../styles/index.scss";
export default function App({ Component, pageProps }: AppProps): React.ReactElement {
const apolloClient = useApollo(pageProps);
return (
<ApolloProvider client={apolloClient}>
<Head>
<title>Salami Slicing</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=0" />
<link rel="icon" type="image/svg+xml" href="/images/logo.svg" />
</Head>
<ScrollControlProvider>
<SystemNotificationContainer>
<Component {...pageProps} />
</SystemNotificationContainer>
</ScrollControlProvider>
</ApolloProvider>
);
}
这个apollo状态以及系统级的一些通知提示类的东西。
修改document
如果你有自定义document的需求,比如自定义document的header之类,或者需要css-in-js之类的库,需要添加_document.js文件:
image.png
/* eslint-disable */
// copied from https://github.com/microsoft/fluentui/wiki/Server-side-rendering-and-browserless-testing#server-side-rendering
// with some changes. Therefore disable eslint checks
import { resetIds } from "@fluentui/utilities";
import * as React from "react";
import Document, { Head, Html, Main, NextScript } from "next/document";
// Do this in file scope to initialize the stylesheet before Fluent UI React components are imported.
import { InjectionMode, Stylesheet } from "@fluentui/style-utilities";
const stylesheet = Stylesheet.getInstance();
// Set the config.
stylesheet.setConfig({
injectionMode: InjectionMode.none,
namespace: "server",
});
// Now set up the document, and just reset the stylesheet.
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
stylesheet.reset();
resetIds();
const page = renderPage((App) => (props) => <App {...props} />);
return { ...page, styleTags: stylesheet.getRules(true) };
}
render() {
return (
<Html>
<Head>
<style type="text/css" dangerouslySetInnerHTML={{ __html: this.props.styleTags }} />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
这里主要处理@fluentuicss-in-js样式的需要,这段代码摘自@fluentui官网,还没搞明白具体为啥这么写(尴尬……)
一些细节
1,page下的_app.js与index.tsx什么区别
_app.js
将包含您的整个应用程序,这意味着它将在项目的任何页面中呈现。如果你在这个文件中添加一个<div>hello world</div>
,你会在你网站的每一页上看到Hello World。这里有更多的阅读。
index.js
仅当您访问网站的/
路径时才会呈现。每当您创建一个新页面时,您将使用索引文件,例如,您想要一个关于页面,您将有一个关于文件夹,其中包含一个index.js
,所有这些都包含在pages
文件夹中。这里有更多的阅读。
我自己的理解。_app.js是一个父组件,所有页面,最终传到pageProps里了
import '../styles/globals.css'; import Navbar from '../components/Navbar.tsx'; function MyApp({ Component, pageProps }) { return ( <> <Navbar /> <Component {...pageProps} /> </> ); } export default MyApp;
这里 Navbar 在所有页面都有。
参考:
https://www.jianshu.com/p/753cf3719665
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
2020-11-11 待读的一本书:学会提问