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

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

React 將我的狀態更新延遲 1 次迭代

React 將我的狀態更新延遲 1 次迭代

繁花不似錦 2023-04-27 14:58:59
這是更新狀態的函數:    GroupByHandler = (index) =>        {            const temporary = [...this.state.header.groupByHeader];                    if(this.state.header.groupByHeader.includes(this.props.Headers[index]))            {                temporary.splice(index,1);                // console.log("[PivotTable.js]: if statement under GroupByHandler");                // console.log(this.props.Headers[index]);            }            else            {                temporary.push(this.props.Headers[index]);                // console.log("[PivotTable.js]: else statement under GroupByHandler");                // console.log(this.props.Headers[index]);                // console.log(temporary);            }            this.setState({                header: {                    ...this.state.header,                    groupByHeader: temporary                }            });            console.log("[PivotTable.js]: ");            console.log(temporary);            console.log(this.state.header.groupByHeader);            console.log("Temporary: ");            console.log(temporary);        }我的控制臺輸出如下所示:[數據透視表.js]:PivotTable.js:43 [“廣告商”]數據透視表.js:44 []PivotTable.js:45 臨時:PivotTable.js:46 [“廣告商”]我的狀態是這樣的:    state = {            header: {                ActiveHeaderIndex: this.props.ActiveIndex,                isHeaderAscending: true,                groupByHeader: []            }}誰能幫我調試我哪里出錯了?我遵循的方式setState不正確嗎?temporary已更新但setState由于某種原因未更新。
查看完整描述

2 回答

?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

你能這樣試試嗎

 this.setState( 
      Object.assign(this.state.header, { groupByHeader: temporary })
    );


查看完整回答
反對 回復 2023-04-27
?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

如果您想在setState工作后立即獲得更新狀態,則 setState 正在異步工作,那么您需要使用如下所示的回調。嘗試一下。


this.setState(

{

? header: {

? ? ...this.state.header,

? ? groupByHeader: temporary

? }

},

() => console.log(this.state.header.groupByHeader)

);

查看完整回答
反對 回復 2023-04-27
  • 2 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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