关于react.js:助力ssr使用concent为nextjs应用加点料

开源不易,感激你的反对,❤ star concent^_^

序言

nextjs是一个十分风行的 React 服务端渲染利用框架,它很轻量,简略易上手,社区沉闷,所以当咱们应用react写一个须要ssr(server side render)的利用的话,根本都会首选nextjsconcent是一个新生代的react状态治理计划,它内置依赖收集零碎,同时兼具备0入侵、可预测、渐进式、高性能的特点,并提供了lifecylecomposition api等灵便的api且写法超级简略,让你轻松驾驭超大规模的react利用。

Hello next

这里咱们将应用create-next-app命令来装置一个根底的next示例利用

npx create-next-app hello-next

执行结束后,能够看到一个如下的目录构造

|____public
|____pages
| |____ _app.js   // next利用默认的根组件
| |____index.js   // 默认首页
| |____api        // api路由文件
| | |____hello.js 

之后咱们在我的项目根目录执行npm run dev将看到一个由next驱动的ssr默认首页

Hello concent

这里咱们将应用create-react-app命令来装置一个根底的concent示例利用

npx create-react-app hello-concent --template concent-ts

执行结束后,能够看到一个如下的目录构造

|____index.tsx
|____App.tsx
|____types            // store的类型定义处
|____features           // 性能组件列表
| |____counter          // counter性能
| | |____Counter.tsx        // counter组件
| | |____model            // counter模型(蕴含state,reducer,computed)
|____models            // 其它全局通用的模型定义
|____configs

进入我的项目目录执行npm i,而后执行npm start即可看到一个默认的计数器页面

你也能够点击这里在线理解和编辑它。

当然了在已有的我的项目里集成concent里也超级简略,因为它无需顶层提供Provider,只须要提前配置好模型即可。

import { run } from 'concent';

run({ // 定义一个counter模型
  counter: {
    state: { num: 1, bigNum: 10 },
    reducer: {
      add(payload, moduleState) {
        return { num: moduleState + 1 };
      },
      async asyncAddBig() {
        await new Promise(resolve => setTimeout(resolve, 1000));
        return { bigNum: moduleState + 10 };
      }
    },
    computed: {
      doubleNum: ({ num }) => num * 2, // 仅当num发生变化才触发此函数
    }
  }
})

之后就能够全局即插即用啦,类组件和函数组件都能够用同样的形式去读取数据或调用办法,敲重点啦,如果ui处是有条件语句管制是否要生产状态或衍生数据的话,举荐提早解构的写法,这样能够让concent在每一轮渲染结束后收集到视图对数据的最小粒度依赖

// ###### 函数组件
function Demo(){
  // 如 state 和 moduleComputed 是按需读取的,举荐提早解构的写法
  const { state: { num, numBig }, moduleComputed: { doubleNum }, mr } = useConcent('counter'); 
  // ... ui 逻辑,绑数据、绑办法
}

// ###### 类组件
const DemoCls = register('counter')(
  class DemoCls extends React.Component{
   render(){
      const { state: { num, numBig }, moduleComputed: { doubleNum }, mr } = this.ctx; 
      // ... ui 逻辑,绑数据、绑办法
    }
  }
)

在next里引入concent

next的根底示例目录里有个_app.js文件,它是next利用的根组件

import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

因应用concent之前必须提前配置好模型,所以咱们只需提前创立一个runConcent.js文件

import { run } from 'concent'
import * as models from './models';

run(models);

而后在_app.js文件引入即可,这样根组件下的所有子组件都可能正确获取到store的数据和调动store的办法了。

import '../styles/globals.css'
+ import './runConcent'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

接着咱们在next的pages目录下创立一个counter.js文件,代表这是一个页面组件,这样浏览器端能够用/counter路由来拜访到这个组件的渲染视图了。

import React from 'react'
import { useConcent } from 'concent'
import router from 'next/router'

// use next/router to do browser side router jump
function toHomePage(){
  router.push('/');
}

export default function Counter() {
  const { state, mr, moduleComputed } = useConcent('home')

  return (
    <div>
      this is counter page
      <h1>num: {state.num}</h1>
      <h1>doubleNum: {moduleComputed.doubleNum}</h1>
      <button onClick={mr.add}>add</button>
      <button onClick={toHomePage}>to home page</button>
    </div>
  );
}

功败垂成,一个接入了concentnext利用就这样产生了,是不是特地简略呢?^_^

getServerSideProps 也是同样相似的做法来做哦,它们只是执行机会不同,getServerSideProps是每次申请页面都会执行,而getStaticProps是构建时执行。

反对预渲染

next提供两种级别的预渲染接口,即getServerSidePropsgetStaticProps,两种的区别是执行机会不同,getServerSideProps是每次申请页面都会执行,而getStaticProps是构建时执行,咱们先解决getServerSideProps这种状况吧,看看如何汇合concent做预渲染反对。

首先咱们不思考concent的存在,在next里做预渲染反对,只须要在你的页面组件里裸露一个getServerSideProps接口即可。

// 此函数在每次申请改页面时被调用
export async function getServerSideProps() {
  // 调用内部 API 获取博文列表
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // 通过返回 { props: posts } 对象,PostPage 组件在渲染时将接管到 `posts` 参数
  return {
    props: { posts },
  }
}

function PostPage({ posts }) { // 这里接管到了 posts 参数
  // Render posts...
}

export default PostPage

之所以Blog可能接到posts,除了裸露这个getServerSideProps这个接口之外,咱们再察看一下_app.js这个根组件文件内容,能够发现关键点所在!

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}
export default MyApp

参数列表里的pageProps即是getServerSideProps返回后果里props指向的对象,而后next将其透传到指标页面组件上,所以咱们才可能在PostPage参数列表里解构出posts

所以咱们的切入点就能够从这里动手了,咱们把getStaticProps的返回后果做一下格局束缚,形如{module:string, state: object}这样的构造,而后在_app.js文件里记录到store即可

// 此函数在每次申请时被调用
export async function getServerSideProps() {
  // 调用内部 API 获取博文列表
  await delay();
  const posts = [
    { id: 1, name: 'post1 -----' },
    { id: 2, name: 'post2 --- welcome to use concent' },
  ];
  // 这个返回对象会透传给根组件的pageProps,在此返回状态所属的模块和状态实体对象
  // 在那里将状态记录到store
  return {
    props: {
      module: 'test',
      state: { posts },
    }
  };
}

此时的根组件文件扭转如下

import '../styles/globals.css';
+ import './runConcent';
+ import { setState } from 'concent';

function MyApp({ Component, pageProps }) {
  // 这里记录 getServerSideProps 的返回状态到store的对应模块
+  if (pageProps.module) {
+    setState(pageProps.module, pageProps.state);
+  }
  return <Component {...pageProps} />
}
export default MyApp;

而后咱们实现的页面组件post-page代码如下

const PostList = React.memo(function () {
  const { state } = useConcent('test');
  return (
    <div>
      {state.posts.map(item => <h3 key={item.id}>{item.name}</h3>)}
    </div>
  );
});

const PostLength = React.memo(function () {
  const { state } = useConcent('test');
  return <h1>{state.posts.length}</h1>;
});

export default function PostPage() {
  return (
    <div>
      <h1>this is post page</h1>
      <PostList />
      <PostLength />
      <button onClick={toHomePage}>to home page</button>
    </div>
  );
}

接着咱们关上浏览器拜访/post-page页面吧,点击查看源码将会看到这是一个服务器端预渲染的页面

同理,咱们也可将getServerSideProps替换为getStaticProps,下面的整个流程将仍然失常工作,欢送各位看官clone示例代码来亲自体验一下。

git clone https://github.com/concentjs/ssr-demo-1

附录

doc

  • next-js doc
  • concent doc

CloudBase CMS

欢送小哥哥们来撩CloudBase CMS ,打造一站式云端内容管理系统,它是云开发推出的,基于 Node.js 的 Headless 内容治理平台,提供了丰盛的内容治理性能,安装简单,易于二次开发,并与云开发的生态体系紧密结合,助力开发者晋升开发效率。

concent已为其治理后盾提供强力反对,新版的治理界面更加好看和体贴了。

FFCreator

也欢送小哥哥们来撩FFCreator,它是一个基于node.js的轻量、灵便的短视频加工库。您只须要增加几张图片或视频片段再加一段背景音乐,就能够疾速生成一个很酷的视频短片。

FFCreator是一种轻量又简略的解决方案,只须要很少的依赖和较低的机器配置就能够疾速开始工作。并且它模仿实现了animate.css90%的动画成果,您能够轻松地把 web 页面端的动画成果转为视频,真的很给力。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理