首页 > 解决方案 > 反应 - 无法读取未定义的属性'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>
                </>
        );
    }
}

标签: reactjs

解决方案


首次加载组件时,dataQuestion 的值将为空,因此 的值dataQuestion[this.state.step]将是未定义的。

因此,您必须使用问号(?)检查该值是否已定义或未定义。

console.log(dataQuestion[this.state.step]?.question_desc)

推荐阅读