Nextjs了解内容
warning:
这篇文章距离上次修改已过202天,其中的内容可能已经有所变动。
Next.js 是一个用于在服务端渲染 React 应用程序的框架,它提供了很多功能,如自动代码分割、自动静态优化、路由预加载等。
以下是一些 Next.js 的常用方法和概念:
- 获取数据:Next.js 提供了两种方法获取数据,一种是通过 getInitialProps 方法,它可以在页面初始化时获取服务器端的数据,并渲染页面。另一种是通过 next/server 中的 fetch 方法,可以在客户端或服务器端使用。
import fetch from 'isomorphic-unfetch';
async function getData() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return data;
}
export default async function Page() {
const data = await getData();
return <div>{data}</div>;
}
- 静态导入:Next.js 支持静态导入,可以导入 JSON, CSS, CSS module, Images 等静态资源。
import Image from 'next/image';
import styles from './styles.module.css';
import data from './data.json';
function Home() {
return (
<div className={styles.container}>
<Image src="/example.jpg" alt="example image" />
<p>{data.text}</p>
</div>
);
}
export default Home;
- 动态导入:Next.js 支持动态导入,可以根据需要按需加载页面或组件。
import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(import('../components/component'), {
ssr: false,
});
function Home() {
return (
<div>
<Header />
<DynamicComponent />
</div>
);
}
export default Home;
- 路由:Next.js 使用文件系统作为路由,每个页面的组件都是通过文件系统的路径来定义的。
// pages/about.js
function About() {
return <div>About</div>;
}
export default About;
- 自定义服务器:Next.js 允许你自定义服务器,可以用来配置自定义行为或集成现有的服务器。
// server.js
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === '/a') {
app.render(req, res, '/a', query);
} else if (pathname === '/b') {
app.render(req, res, '/b', query);
} else {
handle(req, res, parsedUrl);
}
}).listen(3000, () => {
console.log('Running on http://localhost:3000');
});
});
- 导出静态页面:Next.js 支持导出静态页面,可以用于预渲染或生成静态站点。
// pages/index.js
function Home() {
return <div>Home</div>;
}
export default
评论已关闭