2016-10-08 16 views
0

フラックス(redux)実装なしでマークアップをレンダリングする前に、レスポンスサーバー側でデータの非同期をロードする実装が見つかりませんでした。レスキューサーバー側のコンポーネントを非同期データでレンダリングする方法

class Home extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = {meta: []}; 
    } 

    componentDidMount() { 
    Request.get('http://example.com/api/users').then((resp) => { 
     this.setState({meta: resp.body}); 
    }); 

    } 

    render() { 
    return (
     <div> 
     {this.state.meta.map((m, i) => { 
      <p key={i}>{m.user}</p> 
     })} 
    ); 
    } 
} 

ルータファイル(router.js): はここビュー(一緒にAPIとビューの両方)です

export default (
    <Route component={App} path="/"> 
     <IndexRoute component={Home}/> 
    </Route> 
); 

そして、これは私が(反応-ルータで)サーバー上で使用するものです

app.use((req, res) => { 

    Router.match({routes: routes, location: req.url}, (err, redirectLocation, renderProps) => { 
     if(err) res.status(500).send(err.message); 

     else if(redirectLocation) 
      res.status(302).redirect(redirectLocation.pathname + redirectLocation.search); 

     else if(renderProps) { 
       var html = ReactDOM.renderToString(<RouterContext {...renderProps}/>); 
       res.render("layout", {body: html}); 
     } 
     else res.status(404).send("Page not Found"); 
    }) 
}); 

私はいくつかの基本的なことを知っている各ルータのURLを呼び出すと、その後renderToString()を解決します。しかし、私は反応ルータでそれを行う方法を理解していません。 私はライブラリやflux、reduxの実装を使いたくありません。

答えて

0

getComponent小道具をreact-routerに使用すると、このような状況に対処できます。

//route.js 
    function fetchAndGetComponent(location,callback){ 
    Request.get('http://example.com/api/users').then((resp) => { 
     let meta = resp.body; 
     callback(null,() => <Home meta={meta} />); 
    }); 
    } 

    <Route component={App} path="/"> 
     <IndexRoute getComponent={fetchAndGetComponent}/> 
    </Route> 
+0

これは便利です。このデータをクライアントで共有する方法を知っていますか? –

+0

'react-router'の 'match'関数を使って' routes'モジュールを 'window.location'とマッチさせ、' render'関数を 'react-dom'から' match 'クライアントでの関数 –

関連する問題