即使我调用bind()也未定义ReactJS状态

时间:2020-05-03 20:07:24

标签: javascript reactjs

我创建了一个从孩子那里叫来的事件。

但是,当事件引发时,this.state是不确定的。

我什至叫bind!发生了什么事?

如何从孩子提出的组件中的函数内部访问状态?

constructor(props) {
    super(props);

    this.state = {
        showQuestion: false,
        showGetStarted: true,
        correctAnswerTotal: 0,
        question: <Question onAnswer={this.handleAnswer}/>,
        emoji: <EmojiView correctQuestionCount="100"/>
    };

    this.handleAnswer = this.handleAnswer.bind(this);
}

handleAnswer(result) {
    let emoji = this.state.emoji;       // error: TypeError: Cannot read property 'emoji' of undefined  
    if (result === true) {
        emoji.props.correctAnswerTotal = emoji.props.correctAnswerTotal + 1;
    } else {
        emoji.props.correctAnswerTotal = 0;
    }
}

编辑:

这是问题组件的要求部分:

questionFourClicked = (user) => {
    let lastQuestion = this.state.lastQuestion;
    if (lastQuestion.correctIndex == 3) {
        // TODO: they got it right!
        var myQuestionModel = new QuestionModel("unused");
        let randomQuestion = myQuestionModel.getRandomQuestion();
        this.setState({lastQuestion: randomQuestion});
        this.props.onAnswer(true);
    } else {
        this.props.onAnswer(false);
    }
}

1 个答案:

答案 0 :(得分:1)

为了提高知名度: 您创建了Question子组件并将this.handlerAnswer传递给它,然后再将其绑定到上下文,因此只需切换这两个操作的顺序即可。