ES6 writes react component _ this.setState is not a function

problem description

in the process of developing with react, write components with ES6 syntax as follows

const Name = (props) => {
    this.state = {
        data: null,
        visible: false
    };
    
    const open = (data) => {
        this.setState({
            data,
            visible: true
        });
    }
    
    return (
        <div>content</div>
    );
}

prompt Unhandled Rejection (TypeError): _ this.setState is not a function

when executing open ()

tried

const that = this;
that.setState({})

hold the same mistake and ask the boss for an answer.

Mar.31,2021

this is the stateless component. You do not inherit the react method, so there is no lifecycle, no render, no state,setState method. Search the stateless component and you will find out


.

if you write this as a stateless component, there is no lifecycle, and of course there is no react.component method. You need to change it to

.
class Name extends React.Component(){
 constructor() {
    super()
    this.state = {
      
    }
  }
   render (){}


}
Menu