2017-09-25 23 views
1

我寫了一個簡單的ReactJS代碼,其中我試圖從Store類的內部調用render()函數,但出現錯誤。如果我從Store類的外部調用ReactDOM.render()函數,則不能在Store類之外訪問this.state.data。所以請告訴我該怎麼辦?在ReactJS的一個類中調用render()函數

代碼:

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import App from './App.jsx'; 

class Store extends React.Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
     data: 
     [ 
      { 
       name: 'First...', 
       id: 1 
      }, 

      { 
       name: 'Second...', 
       id: 2 
      }, 

      { 
       name: 'Third...', 
       id: 3 
      } 
     ] 
     } 
    }; 

    render(
     <App storeData={this.state.data} />, 
     document.getElementById('app') 
    ); 
} 

錯誤:

ERROR in ./main.js 
Module build failed: SyntaxError: C:/Users/username/Desktop/fluxExample/main.js 
: Unexpected token (31:2) 

    29 | 
    30 | render(
> 31 |   <App storeData={this.state.data} />, 
    |  ^
    32 |   document.getElementById('app') 
    33 | ); 
    34 | } 

@ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-serve 
r ./main.js 
webpack: Failed to compile. 
+0

您的語法根本無效。你似乎也很困惑你的應用程序和React組件。您的商店可能不需要是React組件。 – Axnyff

回答

1

你需要渲染Store組件,然後AppStore一個孩子。 Store中的渲染功能需要返回有效React組件,如

class Store extends React.Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
     data: 
     [ 
      { 
       name: 'First...', 
       id: 1 
      }, 

      { 
       name: 'Second...', 
       id: 2 
      }, 

      { 
       name: 'Third...', 
       id: 3 
      } 
     ] 
     } 
    }; 

    render() { 
     return (
      <App storeData={this.state.data} /> 
     ) 
    } 

} 

ReactDOM.render(
     <Store/>, 
     document.getElementById('app') 
    ); 
相關問題