技术栈就是react,react-redux,react router ,webpack,
基于koa2和mongodb的一个同构博客
还有一些功能和细节还要打磨
github
线上地址
目前有个疑问,
同构的话,react-router前后端共用,部署的时候服务端怎么转义这部分代码?
技术栈就是react,react-redux,react router ,webpack,
基于koa2和mongodb的一个同构博客
还有一些功能和细节还要打磨
github
线上地址
目前有个疑问,
同构的话,react-router前后端共用,部署的时候服务端怎么转义这部分代码?
服务端渲染。 react-router 不要前后端共用。 例如前端 根路由为 /.后台管理路由 /admin. 两个router 文件。通过建立个客户端渲染路由句柄。 服务端路由渲染句柄. 客户端路由句柄如这样:
/*前台后台路由客户端路由渲染*/
import React from 'react';
import {render} from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import configureStore from '../store/configureStore';
require('../favicon.ico');
import '../styles/main.scss';
import { syncHistoryWithStore } from 'react-router-redux';
import {signinSuccess} from '../actions/auth';
export default function renderRouter(routes)
{
const store = configureStore(browserHistory);
const history = syncHistoryWithStore(browserHistory, store);
const token = localStorage.getItem('token'); //获取登入状态
if(token)
{
store.dispatch(signinSuccess(token));
}
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>, document.getElementById('app')
);
}
服务端路由渲染句柄如:
import React from 'react';
import {renderToString} from 'react-dom/server'; //react 服务端渲染
import {Provider} from 'react-redux'; //数据源容器
import {match,RouterContext,createMemoryHistory} from 'react-router'; //react-router 服务端渲染。和路由上下文。创建history
import {syncHistoryWithStore} from 'react-router-redux'; //异步redux 路由
import configureStore from '../../src/store/configureStore';
/*
参数:
1:客户端路由
2:请求
3:响应
4:下一步
5:渲染载体页面 也就是jade页面
6.编译后的react 文件
* */
export default function routerHandle(routes,req,res,next,html='index',src,css)
{
//创建历史记录
const memortHistory = createMemoryHistory(req.url);
//数据源
const store = configureStore(memortHistory);
//hostory
const history = syncHistoryWithStore(memortHistory,store);
//react 服务段渲染
match({history,routes,location:req.url},(error,redirectLocation,renderProps)=>{
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
const content = renderToString(
<Provider store={store}>
<RouterContext {...renderProps}/>
</Provider>
);
res.render(html, {title: "我的博客", html: content,src:src,css:css});
next();
}
});
}