以下是错误消息:
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'));
答案 0 :(得分:12)
从return
移除constructor
,state
必须是这样的属性
constructor(props) {
super(props);
this.state = { status: true };
}
看看这两个例子
function App() {
return { status: true }
}
App.prototype.render = function() {};
console.log(typeof new App().render);
&#13;
function App() {
this.state = { status: true };
}
App.prototype.render = function() {};
console.log(typeof new App().render);
&#13;
正如您在控制台中看到的那样,您可以在第一个示例undefined
中看到它是因为构造函数App
returns new custom object
,而在第二个示例中您获得了正确的结果;