在ReactJS

时间:2017-09-25 08:58:51

标签: reactjs

我编写了一个简单的ReactJS代码,我试图从Store类中调用render()函数,但是我收到了错误。如果我从Store类外部调用ReactDOM.render()函数,则无法在Store类之外访问this.state.data。那么请告诉我该怎么做?

代码:

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.

1 个答案:

答案 0 :(得分:1)

您需要呈现Store组件,然后App作为Store的孩子。 Store中的render函数需要返回一个有效的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')
    );