2017-09-10 140 views
0

我想服務器端呈現我的網頁以獲得更好的性能,但遇到了我的頁面組件componentDidMount() s沒有被調用的問題。ComponentDidMount()在服務器端渲染

例如,這是我的主模板文件:

import React from 'react'; 
import Cube from './components/Cube/Cube.jsx'; 

class Index extends React.Component { 
    render() { 
    return (
      <html> 
      <head> 
       <title>{this.props.title}</title> 
      </head> 
      <body> 
       <Cube /> 
      </body> 
      </html> 
    ); 
    } 
} 

而且我Cube.jsx: 「嘿!」

import React from 'react'; 

class Cube extends React.Component { 
    componentDidMount() { 
     console.log("Hey!"); 
    } 

    render() { 
     return (
      <div> 
       <h1>Hello</h1> 
      </div> 
     ); 
    } 
} 

export default Cube; 

我沒有看到即使在頁面加載時看到<h1>Hello</h1>,也不會在我的pm2日誌中註銷,也不會在我的Chrome控制檯中註銷。這阻止了我對組件的任何邏輯。

如何解決此問題並使我的子組件的componentDidMount()得到調用?注意我正在使用express-react-views進行服務器端渲染。

+0

我不確定在做服務器端渲染時是否可以使用'componentDidMount()'。我記得看到使用polyfills節點忽略它(?)。 – 82Tuskers

+0

我認爲服務器端渲染只生成靜態html標記。它不包括你的反應代碼。所以你看不到你的日誌。您需要將該包與該標記一起包含在該邏輯中。 –

+0

@Prakashsharma是否指webpack中的'bundle.js'? – MarksCode

回答

0

我想唯一的生命週期掛鉤,將調用服務器端是componentWillMount作爲解釋here

即使是這樣,你就不會看到Chrome的控制檯上輸出。您只可能在您的節點日誌中看到它。

讓我知道這是否回答你的問題。

+0

所以你最好使用'componentWillMount'或'constructor'來獲取JSX元素的數據。如果那是你打算做的。另外,我發現這很有用:http://www.crmarsh.com/react-ssr/ – 82Tuskers