2016-03-22 55 views
1

我創建一個反應和nodejs isomprphic店。 我的問題是如何用SERVER SIDE上的初始數據填充我的組件。 我知道如何使用初始數據填充我的主頁組件,我在「/」路徑中獲取數據並將它們作爲道具傳遞給我的組件。但其他路線呢? 我可以定義多個服務器端路由,但我的網站不再是SPA。 如何才能得到反應路由器客戶端路由和服務器端啓動數據的好處?反應同構和初始數據

回答

2

REDX可以節省您一些時間做這樣的事情。或者你可以在服務器上計算狀態,並將其填充爲狀態存儲應用程序的道具。

React路由器很容易同構,但你必須通過你的狀態。

http://redux.js.org/

這index.jsx是我的榜樣與反應路由器W/O終極版:

"use strict"; 
import React from 'react'; 
import { render } from 'react-dom'; 
import { match, Router, browserHistory } from 'react-router'; 

const injectTapEventPlugin = require('react-tap-event-plugin'); 
injectTapEventPlugin(); 

//for dev tools 
window.React = React; 

const routes = require('./Routes.jsx'); 

const history = browserHistory; 
match({history, routes}, (error, redirectLocation, renderProps) => { 
    render(<Router {...renderProps} />, document.getElementById('app')); 
}) 

和Routes.jsx你會發現這樣的:

"use strict"; 
const React = require('react'); 
import { Router, Route, Link, IndexRoute } from 'react-router' 

const Layout = require("./components/Layout.jsx"); 
const Login = require("./components/Login.jsx"); 
const Home = require("./components/Home.jsx"); 
const NotFound = require("./components/NotFound.jsx"); 

const routes = (
    <Route path="/" component={Layout}> 
     <IndexRoute component={Home}/> 
     <Route path="login" component={Login}/> 
     <Route path="*" component={NotFound}/> 
    </Route> 
); 

module.exports = routes; 
0

我用服務器端的以下組件,用於具有react-router的SPA,傳遞位置prop以及ReactDOMServer.renderToString()中的初始狀態對象()

裁判:React-Router Server Rendering docs

import React, { Component } from 'react'; 
import { createStore, combineReducers } from 'redux'; 
import { Provider } from 'react-redux'; 
import reducers from '../reducers'; 
import routes from '../routes'; 
import { match, RoutingContext } from 'react-router'; 

export default class App extends Component { 
    constructor(props) { 
    super(props); 
    } 

    render() { 
    let reducer = combineReducers(reducers); 
    let store = createStore(reducer, this.props); 
    var component; 

    match({ routes, location: this.props.location }, function (error, redirectLocation, renderProps) { 
     if (error) { 
     component = <p>{error.message}</p>; 
     } else if (renderProps) { 
     component = <RoutingContext {...renderProps} />; 
     } else { 
     component = <p>404 not found</p>; 
     } 
    }) 

    return (
     <Provider store={store}> 
     {component} 
     </Provider> 
    ) 
    } 
}