目錄
8. 在getInitialProps中用Axios獲取遠端數據
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>
)
}