gpt4 book ai didi

javascript - SetState 未定义

转载 作者:行者123 更新时间:2023-12-03 01:16:59 26 4
gpt4 key购买 nike

可能做了一些愚蠢的事情,但如果有人可以帮忙的话。我认为这是未定义的。所以我尝试使用 setState 并收到以下错误。

line 20 Uncaught TypeError: Cannot read property 'setState' of undefined

import React from 'react';

class TimeoutModal extends React.Component {

constructor(props) {
super(props);
this.state = {
timeLeft: 60,
timeoutModal: true
};
}

componentDidMount() {
setInterval(() =>{
this.setState({ timeLeft: this.state.timeLeft - 1 });
}, 1000);
}

handleClick(e) {
this.setState({timeoutModal: false});
}

render() {
console.log(this.props.timeoutStatus);
return (
<div className="timeout-modal">
<div className="timeout-modal__container">
<p>Would you like to continue? {this.state.timeLeft}</p>
<button onClick={this.handleClick} className="timeout-modal__container-button">Yes</button>
</div>
</div>
);
}
}

export default TimeoutModal;

最佳答案

您需要将handleClick事件与当前组件实例绑定(bind)。因此,将 onChange 事件处理程序更改为。

<button onClick={this.handleClick.bind(this)} className="timeout-modal__container-button">Yes</button>

来自doc :

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

当您将它们绑定(bind)到构造函数内然后使用它们时,会更清晰。

constructor(props) {
super(props);
this.state = {
timeLeft: 60,
timeoutModal: true
};
this.handleClick = this.handleClick.bind(this)
}

立即编写处理程序。

<button onClick={this.handleClick} className="timeout-modal__container-button">Yes</button>

关于javascript - SetState 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51965510/

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