Next.js实现react服务器端渲染的方法示例
说明
实现路由跳转、redux
文件版本
- “next”:“^4.2.3”,
- “react”:“^16.2.0”,
- “react-dom”:“^16.2.0”
Next.jsGitHub文档
项目源码
使用
Next.js使用文件体统作为API,可以自动进行服务器端渲染和代码分割
1.安装
yarnaddnextreactreact-dom
2.package.json中添加npmscript
"scripts":{
"dev":"next",
"build":"nextbuild",
"start":"nextstart"
},
3.创建/pages文件夹,其中文件会映射为路由
/pages文件夹是顶级组件文件夹其中/pages/index.js文件会映射文/路由,其他文件根据文件名映射
| 目录结构 | 映射路由 |
|---|---|
| /pages/index.js | / |
| /pages/about.js | /about |
| /pages/home/index.js | /home |
| /pages/home/about.js | /home/about |
每一个路由js文件都会export一个React组件,这个组件可以是函数式的也可以是通过集成React.Component得到的类
exportdefault()=>thisisindexpage;
4.创建/static文件夹,存放静态资源
静态资源文件夹文件会映射到/static/路由下,直接通过http://localhost:3000http://dh.wk163.com/static/test.png访问
5.使用内置组件
定制每个页面的head部分importHeadfrom'next/head';//引入内置组件 exportdefault()=>();indexpage thisisindexpage
6.使用内置组件进行路由跳转
importLinkfrom'next/link'; exportdefault()=>();thisishomeindexpage
toaboutpage
更多Link使用方式
importReact,{Component}from'react';
importLinkfrom'next/link';
exportdefaultclassAboutextendsComponent{
constructor(props){
super(props);
}
render(){
//href值可以是一个对象
consthref={
pathname:'/home',
query:{name:'test'}
};
return(
);
}
}
7.使用内置router方法,手动触发路由跳转
next/router提供一套方法和属性,帮助确认当前页面路由参数,和手动触发路由跳转
importrouterfrom'next/router';
/*
router.pathname==>/home
router.query==>{}
router.route-当前路由
asPath-显示在浏览器地址栏的实际的路由
push(url,as=url)-跳转页面的方法
replace(url,as=url)-跳转页面
*/
更好的方式使用路由–router的withRouter方法
importLinkfrom'next/link';
import{withRouter}from'next/router';
constHome=(props)=>{
//这里的props会得到{router,url}两个属性
//router:{push:ƒ,replace:ƒ,reload:ƒ,back:ƒ,prefetch:ƒ,…}
//url:{query:{…},pathname:"/home",asPath:"/home?name=test",back:ƒ,push:ƒ,…}
console.log(props);
return(
thisishomeindexpage
{/*
toaboutpage
*/}
);
}
exportdefaultwithRouter(Home);
8.使用next-redux-wrapper插件辅助实现redux
1.安装依赖
sudoyarnaddnext-redux-wrapperreduxreact-reduxredux-devtools-extensionredux-thunk
2.创建initializeStore.js一个可以返回store实例的函数
在这个文件中会完成装载中间件、绑定reducer、链接浏览器的redux调试工具等操作
import{createStore,applyMiddleware}from'redux';
import{composeWithDevTools}from'redux-devtools-extension';
importthunkfrom'redux-thunk';
importreducerfrom'../modules/reducers';
constmiddleware=[thunk];
constinitializeStore=initialState=>{
returncreateStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
};
exportdefaultinitializeStore;
3.创建reducer,action
与普通react-redux项目创建reducer,action的方法一致,我把这部分代码都提取到一个名为modules的文件夹中
///modules/reducers.js
import{combineReducers}from'redux';
importaboutfrom'./about/reducer';
//合并到主reducer
constreducers={
about
};
//combineReducers()函数用于将分离的reducer合并为一个reducer
exportdefaultcombineReducers(reducers);
///modules/about/reudcer.js
///about页面的reducer
import{
CHANGE_COUNT
}from'../types-constant';
constinitialState={
count:0
};
consttypesCommands={
[CHANGE_COUNT](state,action){
returnObject.assign({},state,{count:action.msg});
},
}
exportdefaultfunctionhome(state=initialState,action){
constactionResponse=typesCommands[action.type];
returnactionResponse?actionResponse(state,action):state;
}
///modules/about/actions.js
///about页面的action
import{
CHANGE_COUNT
}from'../types-constant';
exportfunctionchangeCount(newCount){
return{
type:CHANGE_COUNT,
msg:newCount
};
}
4.页面中使用
需要用到next-redux-wrapper提供的withRedux高阶函数,以及react-redux提供的connect高阶函数
importReact,{Component}from'react';
importwithReduxfrom'next-redux-wrapper';
import{connect}from'react-redux';
import{bindActionCreators}from'redux';
importAboutComfrom'../components/About/index';
importinitializeStorefrom'../store/initializeStore';
import{changeCount}from'../modules/about/actions';
classAboutextendsComponent{
constructor(props){
super(props);
}
render(){
const{about:{count},changeCount}=this.props;
return ;
}
}
constconnectedPage=connect(
state=>({about:state.about}),
dispatch=>({
changeCount:bindActionCreators(changeCount,dispatch)
})
)(About);
exportdefaultwithRedux(initializeStore)(connectedPage);
更多
查看github官网
react-nextgithub上一个next架构为主实现React服务端渲染的模板
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。