yarn next react react-dom --save
複製代碼
{
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
}
}
複製代碼
默認狀況下:php
// ./page/index.js
var num = 1
num ++
console.log(num)
function click () {
console.log(num++)
}
export default () => (
<div onClick={click}>Hello Next.js</div>
)
複製代碼
yarn dev
yarn dev -p 8080 // 指定端口號
複製代碼
運行以上hello world頁面能夠看出,num在服務端終端和瀏覽器控制檯都輸出一次,單個js文件中的全局代碼是服務端和客戶端公用的代碼,一次在全局中處理純服務器邏輯可能會出錯,反之亦然。html
點擊div能夠打印出num,而且遞增,符合react組件邏輯。前端
import {Component} from 'react'
export default class App extends Component {
static async getInitialProps(obj) {
console.log(obj)
console.log('where called')
var fetch = (url) => {
return new Promise((res, rej) => {
res('獲取數據而後渲染')
})
}
let response = await fetch('/static/demo.json')
console.log(response)
return {response}
}
state = {
num: 1
}
add = () => {
this.setState((state) => {
return state.num++
})
}
render () {
return (
<div> <div>{this.props.response}</div> <div>{this.state.num}</div> <button onClick={this.add}>++</button> </div>
)
}
}
複製代碼
<div>獲取數據而後渲染</div><div>1</div><button>++</button></div></div>
複製代碼
Next.js 支持 IE11 和全部的現代瀏覽器使用了@babel/preset-env。爲了支持 IE11,Next.js 須要全局添加Promise的 polyfill。有時你的代碼或引入的其餘 NPM 包的部分功能現代瀏覽器不支持,則須要用 polyfills 去實現。react
原文連接git
【完】 喜歡的歡迎 star && issuees6