Next.js實(shí)現(xiàn)react服務(wù)器端渲染的方法示例
說明
實(shí)現(xiàn) 路由跳轉(zhuǎn)、redux
文件版本
- “next”: “^4.2.3”,
- “react”: “^16.2.0”,
- “react-dom”: “^16.2.0”
使用
Next.js 使用文件體統(tǒng)作為API,可以自動(dòng)進(jìn)行服務(wù)器端渲染和代碼分割
1. 安裝
yarn add next react react-dom
2. package.json 中添加 npm script
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
3. 創(chuàng)建 /pages 文件夾,其中文件會(huì)映射為路由
/pages 文件夾是頂級(jí)組件文件夾 其中 /pages/index.js 文件會(huì)映射文 / 路由,其他文件根據(jù)文件名映射
| 目錄結(jié)構(gòu) | 映射路由 |
|---|---|
| /pages/index.js | / |
| /pages/about.js | /about |
| /pages/home/index.js | /home |
| /pages/home/about.js | /home/about |
每一個(gè)路由js文件都會(huì) export 一個(gè) React 組件,這個(gè)組件可以是函數(shù)式的也可以是通過集成 React.Component 得到的類
export default () => <div>this is index page </div>;
4. 創(chuàng)建 /static 文件夾,存放靜態(tài)資源
靜態(tài)資源文件夾文件會(huì)映射到 /static/ 路由下,直接通過 http://localhost:3000/static/test.png 訪問
5. 使用內(nèi)置組件 <head> 定制每個(gè)頁面的 head 部分
import Head from 'next/head'; // 引入內(nèi)置組件
export default () => (
<div>
<Head>
<title>index page</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width"/>
</Head>
<div>this is index page</div>
</div>
);
6. 使用內(nèi)置組件 <Link> 進(jìn)行路由跳轉(zhuǎn)
import Link from 'next/link';
export default () => (
<div>
<p>this is home index page</p>
<Link href="/about" rel="external nofollow" rel="external nofollow" >
<a> to about page</a>
</Link>
</div>
);
更多 Link 使用方式
import React, {Component} from 'react';
import Link from 'next/link';
export default class About extends Component {
constructor(props) {
super(props);
}
render() {
// href 值可以是一個(gè)對(duì)象
const href = {
pathname: '/home',
query: {name: 'test'}
};
return (
<div>
<p>this is about page </p>
<img src="/static/test.png" alt="test"/>
{/* replace 覆蓋歷史跳轉(zhuǎn) */}
<Link href={href} replace>
<a>click to home index page</a>
</Link>
</div>
);
}
}
7. 使用內(nèi)置 router 方法,手動(dòng)觸發(fā)路由跳轉(zhuǎn)
next/router 提供一套方法和屬性,幫助確認(rèn)當(dāng)前頁面路由參數(shù),和手動(dòng)觸發(fā)路由跳轉(zhuǎn)
import router from 'next/router';
/*
router.pathname ==> /home
router.query ==> {}
router.route - 當(dāng)前路由
asPath - 顯示在瀏覽器地址欄的實(shí)際的路由
push(url, as=url) - 跳轉(zhuǎn)頁面的方法
replace(url, as=url) - 跳轉(zhuǎn)頁面
*/
更好的方式使用路由 – router 的 withRouter 方法
import Link from 'next/link';
import {withRouter} from 'next/router';
const Home = (props) => {
// 這里的 props 會(huì)得到 {router, url} 兩個(gè)屬性
// router: {push: ƒ, replace: ƒ, reload: ƒ, back: ƒ, prefetch: ƒ, …}
// url: {query: {…}, pathname: "/home", asPath: "/home?name=test", back: ƒ, push: ƒ, …}
console.log(props);
return (
<div>
<p>this is home index page </p>
{/* <Link href="/about" rel="external nofollow" rel="external nofollow" >
<a> to about page</a>
</Link> */}
</div>
);
}
export default withRouter(Home);
8. 使用 next-redux-wrapper 插件輔助實(shí)現(xiàn) redux
1. 安裝依賴
sudo yarn add next-redux-wrapper redux react-redux redux-devtools-extension redux-thunk
2. 創(chuàng)建 initializeStore.js 一個(gè)可以返回 store 實(shí)例的函數(shù)
在這個(gè)文件中會(huì)完成裝載中間件、綁定reducer、鏈接瀏覽器的redux調(diào)試工具等操作
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import reducer from '../modules/reducers';
const middleware = [thunk];
const initializeStore = initialState => {
return createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
};
export default initializeStore;
3. 創(chuàng)建 reducer , action
與普通 react-redux 項(xiàng)目創(chuàng)建 reducer, action 的方法一致,我把這部分代碼都提取到一個(gè)名為 modules的文件夾中
// /modules/reducers.js
import { combineReducers } from 'redux';
import about from './about/reducer';
// 合并到主reducer
const reducers = {
about
};
// combineReducers() 函數(shù)用于將分離的 reducer 合并為一個(gè) reducer
export default combineReducers(reducers);
// /modules/about/reudcer.js
// /about 頁面的 reducer
import {
CHANGE_COUNT
} from '../types-constant';
const initialState = {
count: 0
};
const typesCommands = {
[CHANGE_COUNT](state, action) {
return Object.assign({}, state, { count: action.msg });
},
}
export default function home(state = initialState, action) {
const actionResponse = typesCommands[action.type];
return actionResponse ? actionResponse(state, action) : state;
}
// /modules/about/actions.js
// /about 頁面的 action
import {
CHANGE_COUNT
} from '../types-constant';
export function changeCount(newCount) {
return {
type: CHANGE_COUNT,
msg: newCount
};
}
4. 頁面中使用
需要用到 next-redux-wrapper 提供的 withRedux 高階函數(shù),以及 react-redux 提供的 connect 高階函數(shù)
import React, { Component } from 'react';
import withRedux from 'next-redux-wrapper';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import AboutCom from '../components/About/index';
import initializeStore from '../store/initializeStore';
import { changeCount } from '../modules/about/actions';
class About extends Component {
constructor(props) {
super(props);
}
render() {
const { about: { count }, changeCount } = this.props;
return <AboutCom count={count} changeCount={changeCount} />;
}
}
const connectedPage = connect(
state => ({ about: state.about }),
dispatch => ({
changeCount: bindActionCreators(changeCount, dispatch)
})
)(About);
export default withRedux(initializeStore)(connectedPage);
更多
查看 github官網(wǎng)
react-next github上一個(gè)next架構(gòu)為主實(shí)現(xiàn)React服務(wù)端渲染的模板
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React使用PropTypes實(shí)現(xiàn)類型檢查功能
這篇文章主要介紹了React高級(jí)指引中使用PropTypes實(shí)現(xiàn)類型檢查功能的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02
React在定時(shí)器中無法獲取狀態(tài)最新值的問題
這篇文章主要介紹了React在定時(shí)器中無法獲取狀態(tài)最新值的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
使用react-virtualized實(shí)現(xiàn)圖片動(dòng)態(tài)高度長(zhǎng)列表的問題
一般我們?cè)趯憆eact項(xiàng)目中,同時(shí)渲染很多dom節(jié)點(diǎn),會(huì)造成頁面卡頓, 空白的情況。為了解決這個(gè)問題,今天小編給大家分享一篇教程關(guān)于react-virtualized實(shí)現(xiàn)圖片動(dòng)態(tài)高度長(zhǎng)列表的問題,感興趣的朋友跟隨小編一起看看吧2021-05-05
React使用useImperativeHandle自定義暴露給父組件的示例詳解
useImperativeHandle?是?React?提供的一個(gè)自定義?Hook,用于在函數(shù)組件中顯式地暴露給父組件特定實(shí)例的方法,本文將介紹?useImperativeHandle的基本用法、常見應(yīng)用場(chǎng)景,需要的可以參考下2024-03-03
React 如何使用時(shí)間戳計(jì)算得到開始和結(jié)束時(shí)間戳
這篇文章主要介紹了React 如何拿時(shí)間戳計(jì)算得到開始和結(jié)束時(shí)間戳,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09
react數(shù)據(jù)管理中的setState與Props詳解
setState?是?React?中用于更新組件狀態(tài)(state)的方法,本文給大家介紹react數(shù)據(jù)管理中的setState與Props知識(shí),感興趣的朋友跟隨小編一起看看吧2023-10-10
React實(shí)現(xiàn)雙滑塊交叉滑動(dòng)
這篇文章主要為大家詳細(xì)介紹了React實(shí)現(xiàn)雙滑塊交叉滑動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09

