javascript - react - 未捕获的类型错误 : Cannot read property 'setState' of undefined

标签 javascript reactjs

我收到以下错误

Uncaught TypeError: Cannot read property 'setState' of undefined

即使在构造函数中绑定(bind)了 delta。

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
    }
}

最佳答案

这是由于 this.delta 未绑定(bind)到 this

为了在构造函数中绑定(bind)集合this.delta = this.delta.bind(this):

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

    this.delta = this.delta.bind(this);
}

目前,您正在调用绑定(bind)。但是 bind 返回一个绑定(bind)函数。您需要将函数设置为其绑定(bind)值。

关于javascript - react - 未捕获的类型错误 : Cannot read property 'setState' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32317154/

相关文章:

javascript - 使用 npm 进行 react 并输出到浏览器时出现问题

javascript - 如何在我的 div 元素中呈现更新后的状态?

reactjs - React Router V4 使用 Material UI 在 ListItem 内实现 NavLink

reactjs - React Native 在 React context API 和 useState Hook 中更新状态

javascript - "Uncaught TypeError: $ is not a function"与 instafeed

javascript - Sails 1 - 违反一致性 : Attempting to tear down a datastore (`default` ) which is not currently registered with this adapter

javascript - 使用 Pusher API 通知特定用户

javascript - 如何使 componentDidMount() 在渲染之前完成

javascript - HTML 在点击时不运行函数

javascript - React 如何在 render() 中正确调用组件函数