javascript - 状态未定义 no-undef ReactJS?
问题描述
所以我不断收到错误Line 29: 'answers' is not defined no-undef
,我不太确定发生了什么或如何修复它(我对 React 和 JS 很陌生)。谁能解释这意味着什么并给我一些指示?谢谢!
class App extends Component {
constructor(props){
super(props);
this.state = {
key: myUUID,
title: "",
author: "",
questions: [],
answers: []
}
}
addQuestion(){
questionNum++;
this.setState({
answers }, () => {
this.state.answers.concat("hello")
});
}
更新:这是新addQuestion
功能的样子
addQuestion(){
questionNum++;
this.setState({
answers: this.state.answers.concat("hello")
});
}
单击此按钮时我调用此函数<button onClick={this.addQuestion}>Add Question</button>
现在我收到此错误TypeError: Cannot read property 'setState' of undefined
解决方案
我想也许你的意思是这样写,它将this
使用箭头函数绑定到函数:
addQuestion = () => {
questionNum++;
this.setState({
answers: this.state.answers.concat("hello")
});
}
或者
const answers = this.state.answers.concat("hello");
this.setState({ answers });
您编写它的方式answers
是未定义的,并且() => {this.state.answers.concat("hello")}
是对setState
推荐阅读
- mysql - 需要在最近 4 笔交易中获得 MAX 卖出价
- optimization - 与我自己的项目相比,llvm Costmodel Analysis Pass 通过 opt 显示不同的结果
- c# - SSIS导入多个文件忽略空行
- reactjs - 如果我已经从博览会中弹出(分离)应用程序,我可以再次用 JavaScript 编写代码吗?
- android - 每个通知的通知通道 ID 应该是唯一的
- python - 使用 Tesseract 和 OpenCV (Python) 从图像中读取文本
- testing - vars.putObject 和 vars.getObject 是否会消耗 jmeter 中的额外内存
- excel - Excel VBA format numbers to specific value in UserForm
- windows - Good practice GCE + Windows: computer name
- ruby-on-rails - Travis 配置条件环境变量