作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码。它基本上只是一个带有事件处理程序的按钮,并且该类应该保存某种状态,到目前为止它只是一个计数器,最初设置为 0。
import React, { Component } from 'react';
// import styles from './SentenceView.css';
export default class SentenceView extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
getNextSentence() {
console.log(this.state.count); // this &
this.setState({count: 2}); // this gives me an error
console.log("Executed");
}
render() {
return (
<div>
{/* <div className={styles.container}> */}
<div>
<h1>SentenceView</h1>
<button onClick={this.getNextSentence}>Next Sentence</button>
</div>
</div>
);
}
}
当我单击 getNextSentence 按钮时,我得到:
SentenceView.js:14 Uncaught TypeError: Cannot read property 'state' of null
我知道这个错误并不罕见,但我还没有在这里找到任何解决方案。
最佳答案
尝试将其添加到底部的构造函数中:
this.getNextSentence = this.getNextSentence.bind(this);
关于javascript - React - 未捕获的类型错误 : Cannot read property 'state' of > null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41577319/
我是一名优秀的程序员,十分优秀!