【问题标题】:React ES6: you may have forgotten to define `render`React ES6:你可能忘记定义 `render`
【发布时间】:2016-08-20 01:22:10
【问题描述】:

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

这是错误信息:

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'));

【问题讨论】:

    标签: reactjs ecmascript-6


    【解决方案1】:

    constructor 中删除return,并且state 必须是这样的属性

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

    Example

    看看这两个例子

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

    function App() {
      this.state = { status: true };
    }
    App.prototype.render = function() {};
    
    console.log(typeof new App().render);

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

    【讨论】:

    • 哇,这是一个陷阱......所以在 JavaScript 中,如果你从构造函数()返回一些东西,它会将它交换为对象。棘手的错误,幸运地找到了您的解决方案,谢谢!
    猜你喜欢
    • 2023-04-05
    • 2021-05-20
    • 2021-12-13
    • 2021-11-19
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    相关资源
    最近更新 更多