【问题标题】:Why is not the state updated?为什么状态不更新?
【发布时间】:2019-02-10 23:34:14
【问题描述】:

我有一个函数可以通过更改更新状态并添加一个值,但“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函数时它会是异步的

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    check 为真时,您调用setState 的方式存在问题。

    应该是

    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)}
    )
    

    【讨论】:

    • 这出了问题,将我的数组“响应”更改为 current_question_id 的数量
    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2021-08-04
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多