N
N
Ninja Mate2016-04-19 18:08:02
JavaScript
Ninja Mate, 2016-04-19 18:08:02

Why does the Cannot read property 'setState' of undefined error occur?

Where is the error in the resetUsers: this.handleAlertDismiss method?
Cannot read property 'setState' of undefined

super(...props);
        this.state = {
           showModal: true,
            ...
           //handleAlertDismiss Не работает
            resetUsers: this.props.resetUsers || this.handleAlertDismiss
        };
        this.handleAlertDismiss = this.handleAlertDismiss.bind(this);
    }

    handleAlertDismiss() {
        this.setState({showModal: false});
    }

    render() {
        const {resetUsers} = this.state;
        return (
            <div>
                <Modal show={this.state.showModal} bsSize="sm">
                         <Alert bsStyle={this.state.alertStyle} 
                                   showModal={this.state.showModal} 
                                   onDismiss={ this.state.resetUsers }>
                           
                                <Button onClick={resetUsers} >Gotcha!</Button>
                        </Alert>
                </Modal>
            </div>
        );

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2016-04-19
@victorzadorozhnyy

There is an error in your constructor. You first put the value of the link to the function in this.state.resetUsers , then you redefine this function through bind, but this.state.resetUsers remains with the old link. In javascript, copying and passing is done by sharing
Solutions
1) Bindim in the forehead
2) Instead

this.handleAlertDismiss = this.handleAlertDismiss.bind(this);
write
3) Making the right link
constructor() {
    super(...props);
    this.handleAlertDismiss = this.handleAlertDismiss.bind(this);
    this.state = {
      showModal: true,
      resetUsers: this.handleAlertDismiss
    };
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question