React ES6:您可能忘记定义`render`

时间:2016-04-26 09:42:32

标签: reactjs ecmascript-6

我停了一会儿,不知道哪里出错,请帮帮我

以下是错误消息:

Warning: App(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.
Uncaught TypeError: inst.render is not a function

这是我的代码:

import React from 'react';
import ReactDOM from 'react-dom';

console.log('Start')

export class App extends React.Component{
  constructor(props) {
     super(props);
     console.log('getInitialState');
     return { status:true }
  }
  toggleState(){
    this.setState({status: !this.state.status})
  }
  render() {
    console.log('render');
        return (
           <div>
              <h1 onClick={this.toggleState}>Hello</h1>
           </div>
        );
     }

} 

ReactDOM.render(<App name='Vipul' />,document.getElementById('app'));

1 个答案:

答案 0 :(得分:12)

return移除constructorstate必须是这样的属性

constructor(props) {
  super(props);
  this.state = { status: true };
}

Example

看看这两个例子

&#13;
&#13;
function App() {
   return { status: true }
}
App.prototype.render = function() {};
console.log(typeof new App().render);
&#13;
&#13;
&#13;

&#13;
&#13;
function App() {
  this.state = { status: true };
}
App.prototype.render = function() {};

console.log(typeof new App().render);
&#13;
&#13;
&#13;

正如您在控制台中看到的那样,您可以在第一个示例undefined中看到它是因为构造函数App returns new custom object,而在第二个示例中您获得了正确的结果;