一、配置next
1、手动配置
mkdir nextDemo
cd nextDemo
npm init -y
/** 配置package.json*/
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev" : "next" ,
"build" : " next build",
"start" : "next start"
}
/** 启动命令*/
npm run dev
或者
yarn dev
2、create-next-app脚手架自动配置
npm install -g create-next-app
npx create-next-app nextDemo
/** 启动命令 */
yarn dev
或者
npm run dev
二、路由生成、跳转、传参和六个钩子事件
1、路由生成
next默认会自动给我们生成好路由,路由生成规则是在项目的根目录下有pages文件夹,pages下文件对应的路由就是文件夹+文件名的形式,比如pages下有一个blog文件夹blog文件夹下有一个header.js文件,那么next默认会生成/blog/header路由
2、路由跳转
(1).采用标签跳转
import Link from "next/link";
<Link href="/"><a>去首页</a></Link>
(2).采用Router.push跳转
import Router from "next/router";
function gotoHeadPage(){
Router.push('/');
}
<button onClick={gotoHeadPage}>去首页</button>
(3).路由传参
/** 传递参数的页面pages/header/page1.js */
import Link from 'next/link';
import Router from "next/router";
import {withRouter} from "next/router"
function Page(){
function gotoHeader(){
Router.push({
pathname:"/",
query:{
name:"首页"
}
})
}
return (
<>
<div>page1</div>
<Link href={{pathname:"/",query:{name:'这是首页'}}}><a>去首页</a></Link>
/**或者写成**/
<Link href="/?name=首页"><a>去首页</a></Link>
/** 函数式的写法 **/
<button onClick={gotoHeader}>去首页</button>
</>
)
}
export default Page;
/** 接收参数的页面pages/index.js **/
import {withRouter} from "next/router";
const Header=({router})=>{
return <>
<h1>{router.query.name}</h1>
</>
}
export default withRouter(Header);
(4).六个钩子事件
三、异步请求数据
getInitialProps
Home.getInitialProps = async () => {
const promise = new Promise((resolve) => {
axios
.post("http://localhost:3001/create", {
name: "wyh",
deadline: "2019-09-08",
content: "老白",
})
.then((res) => {
// console.log(res);
resolve({ ...res });
});
});
return await promise;
};
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Fjbl0MyP-1604122631827)(/Users/wyh/Library/Containers/com.tencent.qq/Data/Library/Caches/Images/19565F7FAADC0B4903FEB9F15229F6C8.jpg)]
上述问题是因为nextjs更新之后造成的,需要采用以下方式进行:
import axios from "axios";
function Page(props) {
console.log("props", props);
return <p>hello world</p>;
}
export default Page;
export const getStaticProps = async () => {
let promise = new Promise((resolve) => {
axios
.post("http://localhost:3001/create", {
name: "wyh",
deadline: "2019-09-08",
content: "123",
})
.then((res) => {
resolve(res.data);
});
});
return {
props: {
list: await promise,
},
};
};
/** next官方把那个弃用了 **/
https://github.com/vercel/next.js/blob/master/errors/gssp-component-member.md
四、jsx style
import Link from "next/link";
import React, { useState } from "react";
function pageOne() {
const [color, setColor] = useState("blue");
function onChangeColor() {
setColor(color === "blue" ? "red" : "blue");
}
return (
<>
<div>这是page1</div>
<Link href="/?name=首页">
<a>去首页</a>
</Link>
<button onClick={onChangeColor}>改变颜色</button>
<style>
{`
div{
color:${color}
}
`}
</style>
</>
);
}
export default pageOne;
五、按需加载第三方模块库
1.常规的加载方式
/** 以moment为例演示常规加载方式 **/
import React, { useState } from "react";
import moment from "moment";
function pageOne() {
const [nowTime, setNowTime] = useState(Date.now());
function onChangeTime() {
setNowTime(moment(nowTime).format());
}
return (
<>
<div>这是page1</div>
<p>现在时间:{nowTime}</p>
<button onClick={onChangeTime}>更换时间格式</button>
</>
);
}
export default pageOne;
2.按需加载
/** 以moment为例演示按需加载方式 **/
import React, { useState } from "react";
function pageOne() {
const [nowTime, setNowTime] = useState(Date.now());
async function onChangeTime() {
const moment = await import("moment");//注意import是异步操作,需要加await,函数前要加async
setNowTime(moment.default(nowTime).format());//第三方按需加载需要使用default加载
}
return (
<>
<div>这是page1</div>
<p>现在时间:{nowTime}</p>
<button onClick={onChangeTime}>更换时间格式</button>
</>
);
}
export default pageOne;
/** 按需加载自己的组件 **/
import React, { useState } from "react";
import moment from "moment";
import dynamic from "next/dynamic";//引入next里的这个方法
const Page = dynamic(import("./page2.js"));//进行懒加载
function pageOne() {
const [nowTime, setNowTime] = useState(Date.now());
async function onChangeTime() {
setNowTime(moment(nowTime).format());
}
return (
<>
<div>这是page1</div>
<Page />
<p>现在时间:{nowTime}</p>
<button onClick={onChangeTime}>更换时间格式</button>
</>
);
}
export default pageOne;
六、友好的SEO操作
/** next提供的head组件 **/
import Head from "next/head";
const MyHeader=()=>{
return <>
<Head>
<title>jsp.com</title>
<meta charset="utf-8"/>
</Head>
</>
}
export defualt MyHeader;
//上面已经封装好了一个页面的头部信息,可以在需要的页面直接调用这个组件
七、让Next.js支持css文件
1、为什么需要让next.js支持css文件
由于Next.js默认不支持css文件的,它用的是style jsx,也就是说它是不支持直接import进行引入css的
2、@zeit/next-css配置让next.js支持css文件
@zeit/next-css它的主要功能就是让Next.js可以加载CSS文件,有了这个包才可以进行配置。
/** 配置@zeit/next-css **/
//在根目录下创建一个next.config.js文件,并输入一下内容
const withCss = require('@zeit/next-css')
if(typeof require !== 'undefined'){
require.extensions['.css']=file=>{}
}
module.exports = withCss({})
3、babel-plugin-import 按需加载antd
https://github.com/vercel/next.js/tree/canary/examples/with-ant-design
加载antd在我们打包的时候会把antd的所有包都打包进来,这样会产生性能问题,让项目加载变得非常的慢,现在的目的是指加载项目中用到的模块,这就需要用到babel-plugin-import。
/** 安装babel-plugin-import **/
npm install babel-plugin-import -S
/** 根目录下穿件.babelrc文件,写入如下内容 **/
{
"presets":["next/babel"], //Next.js的总配置文件,相当于继承了它本身的所有配置
"plugins":[ //增加新的插件,这个插件就是让antd可以按需引入,包括CSS
[
"import",
{
"libraryName":"antd",
"style":"css"
}
]
]
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CpFXNscX-1604122631830)(/Users/wyh/Desktop/版本.png)]
272

被折叠的 条评论
为什么被折叠?



