reactjs - 反应 - 无法读取未定义的属性'question_desc'
问题描述
每当我单击下一个或上一个按钮时,我都会得到这些对象,它会在我的 console.log 中显示如下
这是我要执行的操作console.log(dataQuestion[this.state.step])
(步骤是在我单击时移动索引)
但是当我添加console.log(dataQuestion[this.state.step].question_desc)
以获取 question_desc 时,它会得到无法读取未定义的属性'question_desc'。我不知道我做错了什么。有人可以给我一些答案。
这是我的一段代码。
class QuizForm extends Component {
constructor(props){
super(props)
this.state={
step: 0,
dataQuestion: [],
}
}
// ------------------
componentDidMount(){
axios.get('http://localhost:3000/quiz/'+this.props.quizID)
.then(res=>{
this.setState({
dataQuestion: res.data
})
})
.catch(error => console.log(error))
}
// -------------------
handleNext = ()=>{
if (this.state.step === this.state.dataQuestion.length - 1){
return
}
this.setState({step: this.state.step + 1})
}
handlePrevious = ()=>{
if(this.state.step === 0){
return
}
this.setState({step: this.state.step - 1})
}
// ---------------------
render(){
const {dataQuestion} = this.state
console.log(dataQuestion[this.state.step].question_desc)
return(
<>
<div className="column middle">
<div className="game-details-container">
<h1> Question : <span id="question-number"></span> /</h1>
</div>
<div className="game-quiz-container">
<div className="game-options-container">
<span>
<input type="radio" id="option-one" name="option" className="radio" value="optionA" />
<label htmlFor="option-one" className="option" id="option-one-label">A Answer</label>
</span>
</div>
<div className="next-button-container">
<button onClick = {()=>this.handlePrevious()}>Previous Question</button>
<button onClick = {()=>this.handleNext()}>Next Question</button>
</div>
</div>
</div>
</>
);
}
}
解决方案
首次加载组件时,dataQuestion 的值将为空,因此 的值dataQuestion[this.state.step]
将是未定义的。
因此,您必须使用问号(?)检查该值是否已定义或未定义。
console.log(dataQuestion[this.state.step]?.question_desc)
推荐阅读
- c - 如果指针存储了一个变量的地址,并且本身就是一个变量,那它是不是会创建无限指针并填满整个系统内存呢?
- java - 在 javaFXML 文件中键入以使用 GmapsFX
- postgresql - 使用外键约束更新列是否可以锁定引用的表?
- android - 为什么创建 toast 消息的绑定函数不通过注释通过绑定 OnClick 显示?
- javascript - 选择文件ExtJs后如何重置文件字段
- html - 参考书目和引文的微格式/模式
- javascript - 如何替换字符串和圆形小时中的时间戳?
- ios - uitapgesture 仅在点击 3 次后响应
- apache-spark - 用于预测的 Spark 中的 PMML 执行
- ssh - Plotly 和 JupyterLab:图表未从远程服务器显示