为什么不更新状态?

时间:2019-02-10 23:34:15

标签: reactjs

我有一个可以通过更改来更新状态并添加值的函数,但是'addResponse'函数中的状态并不总是更改:

handleSelected (e, item) {
    this.setState({
        current_component_id: item.id,
    }, () => this.addResponse()
    );
};

上面的调用函数:

addResponse (e) {
    const { enrollment_id, evaluation_id, user_id, question_id, current_component_id, 
    responses, current_question, current_question_id 
    } = this.state;
    console.log(current_component_id)

    if (current_component_id != 0) {

        const newResponse = {
            enrollment_id: enrollment_id,
            evaluation_id: evaluation_id,
            user_id: user_id,
            question_id: current_question_id,
            answer_component: current_component_id,
        };

        function hasAnswer(res) {
            const list_question_id = res.map((item) => {
                return item.question_id
            });
            if (list_question_id.includes(current_question_id)) {
                return true
            } else {
                return false
            }
        }

        if (responses === undefined) {
            this.setState({
                responses: [newResponse]
            } 
            , () => console.log('---------> primeiro', this.state.responses)
            )
        } else {
            const check = hasAnswer(responses);
            if (check) {
                this.setState(prevState => {
                    prevState.responses.map((item, j) => {
                        if (item.question_id === current_question_id) {
                            return item.answer_component = current_component_id
                        }
                        return item ;
                    })
                }
                , () => { console.log('----> questao alterada ', this.state.responses)}
                )

            } else {
                this.setState({
                    responses: [...this.state.responses, newResponse]
                    }
                    , () => console.log('------> questao nova', this.state.responses)
                    );
            }
        }
    }

    // this.nextQuestion();
};

第一个console.log总是正确的,但是其他控制台并不总是更改的,我知道setState是异步的,但是我认为当我调用addResponse函数时,它将是异步的

1 个答案:

答案 0 :(得分:0)

setState为真时,如何调用check会出现问题。

应该是

this.setState(prevState => ({
  responses: prevState.responses.map((item, j) => {
               if (item.question_id === current_question_id) {
                 item.answer_component = current_component_id
               }
               return item ;
             })
})
, () => { console.log('----> questao alterada ', this.state.responses)}
)