鍍金池/ 問答/HTML/ react,this.setState數(shù)據(jù)更新

react,this.setState數(shù)據(jù)更新

這個(gè)方法中我更新currentType的值以后,在fetchQuestionIdList函數(shù)中用currentType作為參數(shù)去調(diào)接口,但是每次currentType都是我上次更新的值,選2傳送1,選3傳送2,選4傳送3....
有什么方法解決這種延遲?或者我跟本不應(yīng)該這樣用它作為參數(shù),而是定義別的變量保存我選的值?this.setState只是用來重新渲染嗎?

 onClickItemType=(item)=>{
    this.setState({
        currentType:{
            code:item.code,
            name:item.name
        },
        isShowTypeList: false
    })
    this.fetchQuestionIdList(this.state.navigationCode)
}

fetchQuestionIdList = async (tfcode) => {
    let params = {
        navigationCode: tfcode,
        typeCode: currentType.code,
        diffCode: currentDiff.code,
        contentFinalFlag: true,
        thirdpartyType: 1
    }
    let systemQuestions = await matchExcerciseApi.getQuestionList(params) || {}
}
回答
編輯回答
綰青絲

this.setState是異步執(zhí)行的,需要在其回調(diào)函數(shù)中獲取更新后的值。

2018年5月24日 13:59
編輯回答
互擼娃

this.setState第二個(gè)傳參是個(gè)回調(diào)函數(shù),這時(shí)候state是更新后的

 onClickItemType=(item)=>{
    this.setState({
        currentType:{
            code:item.code,
            name:item.name
        },
        isShowTypeList: false
    }, () => {
        this.fetchQuestionIdList(this.state.navigationCode)
    })
}

fetchQuestionIdList = async (tfcode) => {
    let params = {
        navigationCode: tfcode,
        typeCode: currentType.code,
        diffCode: currentDiff.code,
        contentFinalFlag: true,
        thirdpartyType: 1
    }
    let systemQuestions = await matchExcerciseApi.getQuestionList(params) || {}
}
2017年8月1日 01:17