Next.js实现react服务器端渲染的方法示例

说明

实现 路由跳转、redux

文件版本

  • “next”: “^4.2.3”,
  • “react”: “^16.2.0”,
  • “react-dom”: “^16.2.0”

Next.js GitHub 文档

项目源码

使用

Next.js 使用文件体统作为API,可以自动进行服务器端渲染和代码分割

1. 安装

yarn add next react react-dom

2. package.json 中添加 npm script

 "scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start"
 },

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 得到的类

export default () => <div>this is index page </div>;

4. 创建 /static 文件夹,存放静态资源

静态资源文件夹文件会映射到 /static/ 路由下,直接通过 http://localhost:3000/static/test.png 访问

5. 使用内置组件 <head> 定制每个页面的 head 部分

  import Head from 'next/head'; // 引入内置组件

  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. 使用内置组件 <Link> 进行路由跳转

  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 值可以是一个对象
   const href = {
     pathname: '/home',
     query: {name: 'test'}
   };

   return (
    <div>
      <p>this is about page </p>
      <img src="/static/test.png" alt="test"/>
      {/* replace 覆盖历史跳转 */}
      <Link href={href} replace>
      <a>click to home index page</a>
      </Link>
    </div>
   );
  }
}

7. 使用内置 router 方法,手动触发路由跳转

next/router 提供一套方法和属性,帮助确认当前页面路由参数,和手动触发路由跳转

  import router from 'next/router';
  /*
    router.pathname ==> /home
    router.query ==> {}
    router.route - 当前路由
    asPath - 显示在浏览器地址栏的实际的路由
    push(url, as=url) - 跳转页面的方法
    replace(url, as=url) - 跳转页面
  */

更好的方式使用路由 – router 的 withRouter 方法

import Link from 'next/link';
import {withRouter} from 'next/router';

const Home = (props) => {
  // 这里的 props 会得到 {router, url} 两个属性
  // 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 插件辅助实现 redux

1. 安装依赖

sudo yarn add next-redux-wrapper redux react-redux redux-devtools-extension redux-thunk

2. 创建 initializeStore.js 一个可以返回 store 实例的函数

在这个文件中会完成装载中间件、绑定reducer、链接浏览器的redux调试工具等操作

  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. 创建 reducer , action

与普通 react-redux 项目创建 reducer, action 的方法一致,我把这部分代码都提取到一个名为 modules的文件夹中

  // /modules/reducers.js
  import { combineReducers } from 'redux';
  import about from './about/reducer';

  // 合并到主reducer
  const reducers = {
    about
  };

  // combineReducers() 函数用于将分离的 reducer 合并为一个 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 高阶函数,以及 react-redux 提供的 connect 高阶函数

  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官网

react-next github上一个next架构为主实现React服务端渲染的模板

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 从零开始最小实现react服务器渲染详解

    前言 最近在写 koa 的时候想到,如果我部分代码提供api,部分代码支持ssr,那我应该如何写呢?(不想拆成 2个服务的情况下) 而且最近写的项目里面也用过一些服务端渲染,如nuxt,自己也搭过next的项目,确实开发体验都非常友好,但是友好归友好,具体又是如何实现的呢,诸位有没有考虑过? 本着求真务实的折腾态度,选了react作为研究对象(主要是vue写的有点多,恶心了),那下面就简单就以最小成本写一个react的服务端渲染 demo 用到的技术栈 react 16 + webpack3 +

  • 简单的React SSR服务器渲染实现

    为什么要SSR 单页应用将UI层和内容都由javascript来渲染,搜索引擎或网页爬虫需要完成的HTML结构,因此单页应用如果只在客户端渲染,不利于SEO,此外尽管我们可以通过按需加载的形式来减少首页加载的js,但是通过js来渲染DOM的时候还是会有一定的时间延迟. 0.前言 服务端渲染在项目中不是刚需的东西,但有的时候也是需要做一个服务端渲染,项目要做服务端渲染当然是有很多好处的 首屏加载快,相比SPA单页应用还要有优势. SEO 优化 利于爬虫,爬取数据. 1. 简介 服务端渲染是指页面的

  • 浅谈React 服务器端渲染的使用

    React 提供了两个方法 renderToString 和 renderToStaticMarkup 用来将组件(Virtual DOM)输出成 HTML 字符串,这是 React 服务器端渲染的基础,它移除了服务器端对于浏览器环境的依赖,所以让服务器端渲染变成了一件有吸引力的事情. 服务器端渲染除了要解决对浏览器环境的依赖,还要解决两个问题: 前后端可以共享代码 前后端路由可以统一处理 React 生态提供了很多选择方案,这里我们选用 Redux 和 react-router 来做说明. R

  • Next.js实现react服务器端渲染的方法示例

    说明 实现 路由跳转.redux 文件版本 "next": "^4.2.3", "react": "^16.2.0", "react-dom": "^16.2.0" Next.js GitHub 文档 项目源码 使用 Next.js 使用文件体统作为API,可以自动进行服务器端渲染和代码分割 1. 安装 yarn add next react react-dom 2. package.j

  • JS简单获得节点元素的方法示例

    本文实例讲述了JS简单获得节点元素的方法.分享给大家供大家参考,具体如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>www.jb51.net - JS几种获得节点元素的方法</title> <script type="application/javascript">

  • js给图片打马赛克的方法示例

    本文主要主要介绍了js给图片打马赛克的方法示例,分享给大家,具体如下: 效果演示 Canvas简介 这个 HTML 元素是为了客户端矢量图形而设计的.它自己没有行为,但却把一个绘图 API 展现给客户端 JavaScript 以使脚本能够把想绘制的东西都绘制到一块画布上. HTML5 标签用于绘制图像(通过脚本,通常是 JavaScript) 不过, 元素本身并没有绘制能力(它仅仅是图形的容器) - 您必须使用脚本来完成实际的绘图任务 getContext() 方法可返回一个对象,该对象提供了用

  • JS+canvas动态绘制饼图的方法示例

    本文实例讲述了JS+canvas动态绘饼图的方法.分享给大家供大家参考,具体如下: 运行效果图如下: 完整代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>www.jb51.net canvas饼状图</title> </head> <body> <canvas id=

  • Ionic + Angular.js实现图片轮播的方法示例

    本文主要给大家介绍了关于Ionic + Angular实现图片轮播的相关资料,分享出来供大家参考学习,需要的朋友们下面来一起看看吧. 先来看看实现的效果图: 方法示例: template文件夹新建slider.html <ion-view view-title="图片轮播"> <ion-content class="padding" scroll="false"> <ion-slides class="sl

  • JS实现iframe自适应高度的方法示例

    本文实例讲述了JS实现iframe自适应高度的方法.分享给大家供大家参考,具体如下: <iframe id="mainFrame" name="mainFrame" src="/zwgk/hsearchview" width="740" frameborder="0" scrolling="no" scrolling="no" frameborder="

  • JS实现css hover操作的方法示例

    本文实例讲述了JS实现css hover操作的方法.分享给大家供大家参考,具体如下: hover我们可以用css的方式写,当然,也可以用js的方式写 <html> <head> <title>js的下拉菜单效果</title> <style type="text/css"> *{ padding:0px; margin:0px; } ul li{ list-style: none; } a{ text-decoration:

  • JS简单实现数组去重的方法示例

    本文实例讲述了JS简单实现数组去重的方法.分享给大家供大家参考,具体如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>JS数组去重</title> <meta http-equiv=&

  • JS生成随机打乱数组的方法示例

    本文实例讲述了JS生成随机打乱数组的方法.分享给大家供大家参考,具体如下: 一.比较乱的排序方法 function fnLuanXu(num) { var aLuanXu=[]; for (var i = 0; i < num; i++) { aLuanXu[i] = i; } for (var i = 0; i < num; i++) { var iRand = parseInt(num * Math.random()); var temp = aLuanXu[i]; aLuanXu[i]

随机推荐