当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

koa-react-router

react-router middleware for koa 2.
授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 凌朗
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

koa-react-router

koa 2 middleware for React server side rendering and routing with react-router 5.

Looking for React Router 3 support see v1 docs.Try React Router 5 though it's awesome!

Usage

To install koa-react-router:

  npm install koa-react-router react react-dom react-router --save

Note: react react-dom & react-router are all peerDependencies of koa-react-router.

koa-react-router can be mounted easily in a koa 2 application like so:

// index.js
  import Koa from 'koa';
  import reactrouter from 'koa-react-router';
  import App from './App';
  import Container from './containers/PageContainer';

  const app = new Koa();

  app.use(reactrouter({
    App,
    onError: (ctx, err) => console.log('I Have failed!!!!'),
    onRedirect: (ctx, redirect) => console.log('I have redirected!'),
    onRender: (ctx) => ({ Container })
  }));

API

koa-react-router requires the following parameters:

App

The App config prop should be a react component that contains one or more React Router 4 Route components to be rendered.For example:

// App.js
  import React from 'react';
  import { Route } from 'react-router';
  import Home from '../containers/Home';
  import Article from '../containers/Article';

 const App = () =>
    <div>
      <h1>This is my App!</h1>
      <Route path="/" component={Home} exact />
      <Route path="/article" component={Article} exact />
    </div>;

  // index.js
  // ...imports
  import App from './App';

  // ... koa app setup
  app.use(reactrouter({
    App,
    // Other callbacks
  }));

preRender

Callback function called before rendering App.This callback can either be a normal function which returns a valid component or it can return a Promise which then resolves and returns a valid component.The function accepts the following parameters:

  • component - The StaticRouter wrapped around the App.

This callback could be used to wrap the component with any other higher-order component before it gets rendered

onError

Callback function called when an error occurs whilst route matching or rendering.
The function accepts the following parameters:

  • ctx - The Koa Context object.
  • err - The error that was caught when matching routes.

onRedirect

Callback function called if a Redirect route is matched.
The function accepts the following parameters:

  • ctx - The Koa Context object.
  • redirectUrl - The url to redirect to.

onRender

Callback function called before sending a response to the client.This function must be supplied, and must return an object that contains the following property:

Container

This should be a React component that wraps around the rendered route.
Typically this will be the template for the page, however this is not mandatory.
As such this component is rendered using renderToStaticMarkup.
The component must accept the children prop and insert it when rendered.For example:

// ./containers/Container
  import React from 'react';

  const Container = (props) =>
    <html lang="en">
      <head>
        <title>Hello Container</title>
      </head>
      <body>
        <div id="app">
          {props.children}
        </div>
      </body>
    </html>;

  export default Container;

This would then be supplied to koa-react-router via the onRender callback like so:

// index.js
  import Koa from 'koa';
  import reactrouter from 'koa-react-router';
  import App from './App';
  import Container from './containers/Container';

  const app = new Koa();

  app.use(reactrouter({
    App,
    onRender: (ctx) => ({ Container })
  }));

As well as the Container property this callback can optionally return:

containerRenderer

Optional function for handling the rendering of a container component.
This function has one argument which is view. This argument is the currently rendered view of the app.
This function may be used if some custom props need to be injected into the container component, such as an initial Redux state.
This function should be used instead of the Container property when returning from onRender.
For example you may want to render the container as follows:

// index.js
  import Koa from 'koa';
  import reactrouter from 'koa-react-router';
  // ...other imports

  const app = new Koa();

  const state = // Create state.

  app.use(reactrouter({
    App,
    onRender: (ctx) => ({
      containerRenderer: (view) =>
      <html lang="en">
        <head>
          <script dangerouslySetInnerHTML={{ __html: state}} />
        </head>
        <body>
          <p>hello container</p>
          <div dangerouslySetInnerHTML={{ __html: view }} />
        </body>
      </html>
    })
  }));

The final page render would look something like:

<html lang="en">
  <head>
    <script>//State config</script>
  </head>
  <body>
    <p>hello container</p>
    <div>
      <!-- View html in here -->
    </div>
  </body>
</html>

id

Optional id for React to use as the base of the app. Default: app

In order for React to re-hydrate the DOM on the client it needs to know where it should attach itself. In a previous version of koa-react-router this was not possible. This property allows you to add a custom root id to the DOM. For example, if you set this to root, the output would look something like.

<html lang="en">
  <head>
    <script>//State config</script>
  </head>
  <body>
    <div id="root">
      <!-- View html in here -->
    </div>
  </body>
</html>

Router Context

React Router 4 added support for a static router context this context can be used in your application, to pass values from your router to other middleware and drive behaviour for routes.
koa-react-router makes this context available on the koa ctx in the following location:

ctx.state.routerContext;

One example of using this context is setting a status in the route context so a later middleware can set that as this response code.The common use case of status is already taken care of. So if one of your routes sets a status prop whilst rendering that will be set as the response status See Not found in the FAQ section for an example.
Use the routerContext for whatever you want in your app, some common recipes will be added to this repo at a later date.

FAQ

This release includes some deprecated props. As React Router has come with some major changes so has koa-react-router.

No more routes prop ?

The routes prop has gone in favour of the App config prop. Where you would have passed in your static routes before you can now pass in your App component that contains the React Router routes. For example:

// App.js
  import React from 'react';
  import { Route } from 'react-router';
  import Home from '../containers/Home';
  import Article from '../containers/Article';

  const App = () =>
    <div>
      <h1>This is my App!</h1>
      <Route path="/" component={Home} exact />
      <Route path="/article" component={Article} exact />
    </div>;

React Router 4 gives you the flexibility to define your routes wherever you want in your app, and so does koa-react-router.

What do I do with routes that are not found ?

The previous version of koa-react-router supported a onNotFound callback. This has been deprecated in favour of defining a status prop on the React Router static context and using a Switch component in your app. For example, our App component may be written as:

import React from 'react';
  import { Route, Switch } from 'react-router';
  import Home from '../containers/Home';
  import Article from '../containers/Article';

  const NotFound = ({ status }) =>
    <Route
      render={({ staticContext }) => {
        if (staticContext) staticContext.status = status;
        return <div>This route has not been found Soz!</div>;
      }}
    />;

  const App = () =>
    <div>
      <h1>This is my App!</h1>
      <Switch>
        <Route path="/" component={Home} exact />
        <Route path="/article" component={Article} exact />
        <NotFound status={404} />
      </Switch>
    </div>;

If not other routes are matched the NotFound component will be rendered, and koa-react-router will set the response code status.

  • 前言 这篇文章讲述如何整合koa,react,nunjacks,koa-router实现一个服务端渲染的工程 koa搭建服务器 // index.js const Koa = require('koa') const app = new Koa() app.use(async(ctx, next) => { ctx.body = 'hello world!' next() }) a

  • 如果你想搭建个项目,一般都是有脚手架的,比如vue的脚手架 vue-cli , react的脚手架 create-react-app ,还有一些其他的,像AntD Admin等。如果想使用koa2 , 也是有一些脚手架的,我常用的就是 koa-generator , 安装它也是很简单: 1.首先需要全局安装 npm install -g koa-generator 2.创建项目 koa2 -e

  • 提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 前言 提示:这里可以添加本文要记录的大概内容: 学习图片上传和保存的过程中,发现post过来的FormData数据无法获取,经过漫长的踩坑过程,实现FormData上传图片,学习文档,仅限于共同进步,大神请绕行。 提示:以下是本篇文章正文内容,下面案例可供参考 一、koa-body 使用koa-body解析post数据,实现Form

  • 概述 前端路由与后端路由的结合一直是一个难题。koa-static这个中间件能够把静态资源“搬到”后端路由上面去,react-create-app在不解构的情况下只会把资源打包到build文件夹,怎么协调koa-static,react-create-app和react-router-dom?我摸索出了一个解决方案,记录下来,供以后开发时参考,相信对其他人也有用。 源码可以参考我的github。

  • koa2 模板引擎模块 koa-views 的使用 我通过koa-generator脚手架构建一个项目用于学习koa2, 现遇到的问题是脚手架官配koa-views,虽说支持很多模板引擎,但没有指出那些模板引擎的高级用法该怎么做? 代码如下: var app = require('koa')() , koa = require('koa-router')() , logger = require(

  • 前端:create-react-app antd axios react 后端:node koa sequelize mysql 作为一个前端小新手,在尝试了一段时间的react前端工作后,就想尝试用node编写web服务,假装自己很厉害。在看了一段时间的node教程+express教程+koa教程等,就开始准备自己写一个小demo。 前端效果图(react+ antd + create-reac

  • react 目录 目录 └─┬ 前端开发指南 ├─┬ 配置环境 │ ├── 配置 Git │ └── 配置前端本地开发环境 ├── 开发流程 ├── 开发规范 ├── 浏览器兼容性 ├── Docker └── 部署 前端开发指南 配置环境 配置 Git 在终端中执行如下命令安装 Xcode 命令行工具 xcode-select --install 注意: Xco

 相关资料
  • React and Koa boilerplate (deprecated. New project available at https://github.com/hung-phan/micro-nextjs) The idea of this repository is to implement all new concepts and libraries which work great f

  • Koa React Universal koa2、react、react-universal-component、koa-webpack-server、async/await、code-splitting、hot-module-replacement、react-router4、redux-thunk This project is dedicated to build simple yet po

  • 内容 Vue,React,微信小程序,快应用,TS , Koa和JS 一把梭。 star ^_^欢迎star,你的star是我更新的动力^_^ 目录 mini-program-demo:小程序 demomini-program-template:小程序 templatereact-koa:react+koa 的全栈demoreact-mobile:react 的移动端 demodva-umi-te

  • koa-mobx-react-starter Along with aiming to use the bleeding-edge of JavaScript (within reason- and all thanks to Babel), this repository represents a choice of frameworks and libraries I think work w

  • Koa-React-Notes-Web This is a simple SPA built using Koa as the backend, Vue as the first frontend, and React as the second frontend. Frontend Vue GitHub Frontend Vue Demo Frontend React GitHub Fronte

  • Koa

    Koa art-template view render middleware. support all feature of art-template. Install npm install --save art-template npm install --save koa-art-template Example const Koa = require('koa'); const ren