0
点赞
收藏
分享

微信扫一扫

前端(react)神级框架nextjs简明总结

芒果六斤半 2021-09-25 阅读 58
日记本

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文件:


/* 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官网,还没搞明白具体为啥这么写(尴尬……)
总结:目前接触到的nextjs的功能就这么多,后面用到更高级的时候我会随时补充……

举报

相关推荐

0 条评论