gpt4 book ai didi

reactjs - react ES6 : you may have forgotten to define `render`

转载 作者:行者123 更新时间:2023-12-03 13:18:49 25 4
gpt4 key购买 nike

我卡了一段时间,不知道哪里错了,请帮助我

这是错误消息:

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

最佳答案

构造函数中删除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);

正如您在控制台中看到的那样,您在第一个示例中得到未定义,这是因为构造函数App returns new custom object ,然后你就会得到正确的结果;

关于reactjs - react ES6 : you may have forgotten to define `render` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36861122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com