Next.js 入门(2)

 

目录

6. 路由跳使用query传递参数和接受参数

7. 路由的6个钩子函数

8. 在getInitialProps中用Axios获取远端数据

9. 使用style JSX编写页面的css样式

​10. LazyLoading实现模块懒加载

 


6. 路由跳使用query传递参数和接受参数


Next 只能用query传递参数

标签跳转Demo

传递对象

编程式跳转Demo

7. 路由的6个钩子函数


 

routeChangeStart

routeChangeComplete

beforeHistoryChange

routeChangeError 路由发生错误,404不算

hashChangeStart

hashChangeComplete

Router.events.on('事件名',(...args)=>{

console.log(...args)

})

8. 在getInitialProps中用Axios获取远端数据


安装

yarn add axios

引入

import axios from 'axios'

使用

PageB.getInitialProps = async()=>{
    const promise = new Promise((resolve)=>{
                  axios('http://rap2.taobao.org:38080/app/mock/250626/api/v1/articleList').then(res=>{
                console.log('远程数据结构:',res)
                resolve(res.data.data)
            }     
        )
    })
    return await promise
}

9. 使用style JSX编写页面的css样式


import React,{useState} from 'react'

export default function Vivi() {
    const [color, setColor] = useState('blue')
    function changeColor(){
        setColor(color=='blue'?'red':'blue')
    }
    return (
        <div>
            <div>Vivi's home</div>
            <button onClick={changeColor}>改变颜色</button>
            <style jsx>
                {`    
                    div{color:${color};}  

                `}
                
            </style>
        </div>
    )
}

10. LazyLoading实现模块懒加载


import React,{useState} from 'react'
import dynamic from 'next/dynamic'
const Tx = dynamic(import('../components/Tx'))

export default function Time() {
   const[nowTime,setTime] = useState(Date.now())
   const changTime=async ()=>{
        const moment = await import('moment')
        setTime(moment.default(Date.now()).format())
    }
    return (
        <div>
            <div>显示时间为:{nowTime}</div>
            <Tx /> 
            <button onClick={changTime}>改变时间格式</button>
        </div>
    )
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章