# Next.js 學習筆記 好看的教學影片:https://www.youtube.com/watch?v=9P8mASSREYM&list=PLC3y8-rFHvwgC9mj0qv972IO5DmD-H0ZH ### 安裝 1. 先確定node.js版本 2. 下載yarn npm install -g yarn (mac無權限)sudo npm install --global yarn 安裝好確定版本yarn --version 3. 創建新project sudo yarn create next-app --typescript 4. 移動到project cd project-test 5. 創建並連結repository sudo git remote add origin 你的repository連結 6. 一直permission denied要sudo很煩 所以先改權限 在終端機輸入whoami 確認自己名稱 XXXXX 再輸入pwd確認檔案位子 /Users/XXXXX sudo chown -R XXXXX:admin /Users/XXXXX/project-test 7. yarn dev啟動 ### Route的觀念 next.js 不像react要用route去定義網址 只要在pages底下依照檔案或資料夾定義就會產生對應的網址 ex. 放入profile.tsx =>localhost:3000/profile nested route:放入product資料夾-product1.tsx=> localhost:3000/product/product1 如果要dynamic route: 放入product資料夾-`[productId].tsx` localhost:3000/product/product1或是localhost:3000/product/product99都會到同個頁面 ```typescript import ( useRouter } from 'next/router' function ProductDetail() { const router = useRouter () const productId = router.query.productId return <h1›Details about product {productId}</h1> } export default ProductDetail //Link的用法: import Link from 'next/link' import { useRouter } from 'next/router' function Home(){ const router = useRouter() const handleClick=()=>{ Router.push('/product') } return( <div> <Link href='/product'> <a>product</a> </Link> </div> ) } ``` 放入404.tsx就會對應到當網址輸入不存在page時的404頁面 總結:  ### Pre-rendering  #### 其一:Static Generation pages用途是在產生對應route跟拿到getstaticprops(datafetch) 所以page中用到的子元件會放在跟pages同層的資料夾components中 - getStaticPaths - getStaticProps getStaticProps的必需參數為paths和fallback。它決定訪問預構建路徑以外的路徑時的行為。 false 其他路由為404 true 如果fallback設置為true,則即使未預構建的路徑也不會為404 透過上述兩者在build玩產生靜態json跟html可以加速網頁載入速度 缺點是staledata的問題 如果數據更新了還是會載入舊數據的頁面 所以nextjs還有另一個機制:incremental static regeneration(ISR) Update static pages after you’ve built your application And can statically generate individual pages without needing to rebuild the entire site 這個key的value是對應到多久要重新build這個單一頁面的秒數 但是這個秒數到了之後需要使用者重新載入頁面才會再trigger rebuild 要再重新載入一次才會是build好的新頁面 #### 其二:Server-side Rendering 不是在build time pre-render而是在request time pre-render getServerSideProps用法跟getStaticProps一樣 只是可以在getServerSideProps中寫serverside code例如fs module之類的
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up