[英]React App - TypeError: Cannot add property setState, object is not extensible
I am very new to coding so please excuse me if my question is not correct. 我对编码非常陌生,所以如果我的问题不正确,请原谅。
I am trying to create a trivia app with react but it doesn't seem to work. 我正在尝试创建一个带有响应的琐事应用程序,但它似乎不起作用。 I am currently working to make the app jump from one question to another when clicking on the answer.
我目前正在努力使应用程序在单击答案时从一个问题跳到另一个问题。
I now receive this error TypeError: Cannot add property setState, object is not extensible . 我现在收到此错误TypeError:无法添加属性setState,对象不可扩展 。 I feel already a little desperate as nothing seems to work for me.
我感到有些绝望,因为似乎没有任何工作对我有效。
Can anyone please help me and guide what I should do next? 谁能帮助我并指导下一步该怎么做?
Trivia.js: Trivia.js:
state = {
questionId: 0
};
nextQuestion () {
this.setState = () => {
return{questionId: this.state.questionId + 1}
};
};
render(){
return(
<div>
<Question
trivia = {quizList[this.state.questionId]}
onClick = {this.nextQuestion}
/>
</div>
)
}
Question.js Question.js
render(){
return(
<div>
<div>
<h2>{this.props.quiz.question}</h2>
</div>
<div>
{this.props.quiz.answers.map((quizAnswer)=>
<li onClick={()=>this.props.onClick()}>
{quizAnswer.ans}
</li>
)}
</div>
</div>
)
}
} }
You're assigning to setState
here: 您在此处分配给
setState
:
this.setState = () => {
return{questionId: this.state.questionId + 1}
};
You need to be calling it: 您需要调用它:
this.setState(state => {
return {
questionId: state.questionId + 1
};
});
Change 更改
this.setState = () => {
return{questionId: this.state.questionId + 1}
};
To 至
this.setState(prevState => ({
return {questionId: prevState.questionId + 1}
))};
I assume that your goal is to have default state for your class 我假设您的目标是为您的班级设置默认状态
What are you trying to do is called Class field and currently is in proposal status so that is why it's not working for you. 您正在尝试做的事情称为“ 班级”字段 ,当前处于提案状态,因此这对您不起作用。 You can either install something that will transpile this into valid javascript or set the default state like this
您可以安装将其转换为有效javascript的内容,也可以设置默认状态,如下所示
class MyComponent extends Component {
constructor(props) {
super(props);
questionId: 0
state = {
};
}
}
You always need to pass in your previous state in the lifecyle as a parameter if you are calling this.setState() in this fashion. 如果以这种方式调用this.setState(),则始终需要将生命周期中的先前状态作为参数传递。
nextQuestion () {
this.setState = (prevState) => {
return{questionId: this.prevState.questionId + 1}
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.