Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ReactJS状态未定义,即使我调用了bind()_Javascript_Reactjs - Fatal编程技术网

Javascript ReactJS状态未定义,即使我调用了bind()

Javascript ReactJS状态未定义,即使我调用了bind(),javascript,reactjs,Javascript,Reactjs,我创建了一个从子级调用的事件 但是,当引发事件时,this.state未定义 我甚至打电话给bind!发生了什么事 如何从子级引发的组件中的函数内部访问状态 constructor(props) { super(props); this.state = { showQuestion: false, showGetStarted: true, correctAnswerTotal: 0, question: <

我创建了一个从子级调用的事件

但是,当引发事件时,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;
    }
}
有关可见性:
在将问题子组件绑定到上下文之前,您创建问题子组件并向其传递
this.handlerAnswer
,因此只需切换这两个操作的顺序,它就会工作。

您能显示完整的组件代码吗,您说的是功能组件,但这是基于类的组件?在任何一种情况下,您都可以创建问题子组件,并在将其绑定到上下文之前将this.handlerAnswer传递给if,因此只需切换这两个操作的顺序,它就会工作。或许您可以尝试检索另一个state属性,查看它是否返回undefined,或者如果它是这个.state.emoji所独有的。@神秘阴影:state是未定义的部分。我试着引用一个(问题),它得到了同样未定义的回答。@Milton:你完全解决了我的问题。我总是在示例中看到构造函数末尾的绑定。我从来没有想到会这样做。谢谢如果你想加上它作为答案,我会给你积分。
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);
    }
}