19同构应用
什么是同构应用
bash
浏览器 服务器
| |
| 初次发送请求 |
|-------------------------------> |
| |
| 返回渲染后的App界面 | 服务器端逻辑
|-------------------------------> |
|
| 客户端操作
|Next.js 创建 React 同构应用
创建页面
- 页面就是 pages 目录下的一个组件
- static 目录映射静态文件
- page 具有特殊静态方法 getInitialProps
在页面中使用其他 React 组件
- 页面也是标准的 node 模块,可以使用其他 React 组件
- 页面会针对性打包,仅包含其引入的组件
使用 Link 实现同构路由
- 使用 next/link 定义链接
- 点击链接时页面不会刷新
- 使用 prefetch 预加载目标资源
- 使用 replace 属性替换 URL
动态加载页面
jsx
import dynamic from 'next/dynamic'
const DynamicComponentWithCustomLoading = dynamic(
import('../components/hello'),
{
loading: () => <p>loading...</p>
}
)
export default () => (
<div>
<Header />
<DynamicComponentWithCustomLoading />
<p>HOME PAGE is here!</p>
</div>
)