亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法讓 setState 同步來解決渲染問題?

有沒有辦法讓 setState 同步來解決渲染問題?

喵喔喔 2021-10-29 17:19:11
我正面臨一個問題。我剛剛發現 setState 是異步的。如果某個條件為真,我將在我的渲染方法中渲染一個組件。船東 ():render() {        const { isFetchingSubject, isFetchingTemplate } = this.props;        return (            ...                            {this.state.showLabelDetails && <Details template={this.props.match.params.templatename} close={this.toggleShowLabelDetails} data={this.state.labelDetails} />}            ...        );    }onclick 按鈕的函數調用:toggleShowLabelDetails = (event) => {        if (!this.state.showLabelDetails) this.setState({ labelDetails: JSON.parse(event.target.value) })        this.setState({ showLabelDetails: !this.state.showLabelDetails });        if (this.state.showLabelDetails) this.setState({ labelDetails: {} })    }狀態:state = {         showLabelDetails: false,        labelDetails: {},     }代碼在做什么的解釋:當用戶點擊按鈕 X 時,它調用函數 toggleShowLabelDetails()它將狀態中的布爾值更改為 true,并將來自按鈕的值添加到作為對象的狀態 labelDetails。狀態改變意味著組件將再次渲染,當條件為真時,它將在屏幕上顯示一個新組件。50% 的情況下它運行良好,但有時我會收到以下錯誤:Uncaught SyntaxError: Unexpected token u in JSON at position 0at Object.parse (<anonymous>)Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. 有什么解決辦法嗎?
查看完整描述

2 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊

您可以將回調傳遞給 setState。


this.setState(

    (state, props) => ({showLabelDetails : !state.showLabelDetails}),

    () => { // Executed when state has been updated

        // Do stuff with new state

        if (this.state.showLabelDetails) {

            this.setState({ labelDetails: {} })

        }

    }

)

順便說一句:你不能依賴 setState 中的 this.state (在 react 文檔中提到),因為 react 可能會批量更新狀態。


查看完整回答
反對 回復 2021-10-29
?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

你可以嘗試做這樣的事情:


class MyComponent extends Component {


function setStateSynchronous(stateUpdate) {

    return new Promise(resolve => {

        this.setState(stateUpdate, () => resolve());

    });

}


async function foo() {

    // state.count has value of 0

    await setStateSynchronous(state => ({count: state.count+1}));

    // execution will only resume here once state has been applied

    console.log(this.state.count);  // output will be 1

}

}


查看完整回答
反對 回復 2021-10-29
  • 2 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號