2016-10-08 2 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에 API 호출을 첨부하고 그 후에 renderToString()을 해결하는 몇 가지 기본적인 것을 알고있다. 그러나 나는 반응 라우터로 어떻게하는지 이해하지 못합니다. 라이브러리 또는 플럭스 또는 redux 구현을 사용하고 싶지 않습니다.

답변

0

react-routergetComponent 소품을 사용하면이 상황을 처리 할 수 ​​있습니다.

//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-dom'의'render' 함수를'match '클라이언트에서의 기능 –

관련 문제