2016-03-22 16 views
1

私は反応とnodejsとisomprphicショップを作成しています。 私の問題は、SERVER SIDEの初期データをコンポーネントに取り込む方法です。 ホームページのコンポーネントに初期データを設定する方法を知っています。データを「/」ルートで取得し、それらをコンポーネントとして自分の小道具として渡します。しかし、他のルートはどうですか? 私は複数のサーバーサイドルートを定義できますが、私のウェブサイトはもはやSPAではありません。 反応ルータのクライアント側ルーティングのベネフィットを取得し、サーバ側でデータを開始するにはどうすればよいですか?反応同形データと初期データ

答えて

2

reduxはこのようなことをする時間を節約できます。または、サーバーで状態を計算し、状態ストアのアプリケーションの小道具にjsonとして設定できます。

リアクタ・ルータは、同形が簡単ですが、あなたはあなたの状態をそのまま渡す必要があります。 index.jsx私の例をだ

http://redux.js.org/

ルータを反応させ、W/O Reduxの:

"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

私が使用:

"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にあなたのような何かを見つけるだろう

ReactDOMServer.renderToString()内の位置propと初期状態オブジェクトを渡す、反応ルータを備えたSPAのサーバ側の次のコンポーネント

REF: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> 
    ) 
    } 
} 
関連する問題