2017-06-18 57 views
1

我需要從服務器端渲染我的React應用程序。爲此,我使用了next.js框架。但我面臨兩個問題。如何使用NextJS和React路由器呈現服務器端反應內容?

首先,我需要動態地爲我的應用程序提供服務。這意味着我需要一個服務器端路由器根據當前的url顯示我的反應組件。

然後,我需要加載一些動態數據之前呈現我的組件。所以我需要將這些數據從節點傳遞給我的反應組件。

這是我目前的狀況:

// In Node.js 
 

 
app.get("/",function(req,res){ 
 

 
    return app.prepare() 
 
    .then(() => handle(req, res)) 
 
    .catch(ex => { 
 
     console.error(ex.stack) 
 
     process.exit(1) 
 
    }) 
 
}) 
 

 
//In React.js 
 

 
import React from 'react' 
 
export default class Index extends React.Component{ 
 
    
 
    render(){ 
 
    return(
 
     <div> 
 
     <p>Hello Server Side Rendered React App from Google Cloud Front</p> 
 
     
 
     </div> 
 
    ) 
 
    } 
 
}

所以,我應該怎麼辦?

回答

1

如果您在React中使用NextJs,您不需要react-router創建頁面,更簡單,您需要創建一個名爲index的目錄,其中包含名爲index.js的組件,它們具有管理導航的組件等上。

看看GitHub文檔,他們已經很好地涵蓋了這些步驟。

https://zeit.co/blog/next2

簡單的例子:

// pages/index.js 
import Link from 'next/link' 
export default() => (
    <div>Click <Link href="/about"><a>here</a></Link> to read more</div> 
) 

// pages/about.js 
export default() => (
    <p>Welcome to About!</p> 
) 
+0

感謝。我不知道下一步是用自己的路由器來。所以它讓事情變得簡單,我猜。 – Jack

+0

@diegochavez,但不會使用鏈接導致第二頁呈現客戶端,而不是服務器端?如果我們想要始終渲染服務器端,那麼我們應該使用普通的html 標籤? – arieljake

相關問題