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

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

React:是否可以停止代碼“閱讀”,直到組件收到新的道具?

React:是否可以停止代碼“閱讀”,直到組件收到新的道具?

幕布斯6054654 2022-01-01 20:37:18
我有一個組件,該組件具有newType在單擊時創建并將其設置為狀態的按鈕。 types來自父組件的外部。如何在this.props.onCreateClick(this.state.selectedDate)運行時停止運行代碼并等待我收到更新,types以便在我更新時types可以運行下一行?它是類組件。該按鈕在 Props 示例中:props: types = [{id: 1, name: 'One'}, {id: 2, name: 'Two'}]this.state = {   selectedDates: [Date],    currentType: null, }<button    onClick={(e) => {        this.props.onCreateClick(this.state.selectedDate)        let newType = this.props.types[this.props.types.length - 1];         this.setState({            selectedDates: [],             currentType: newType.id        })    }}>Create</button>
查看完整描述

2 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

我建議使用Promise


this.state = {

   selectedDates: [Date], 

   currentType: null, 

}


<button

    onClick={() => {

        this.props.onCreateClick(this.state.selectedDate).then(types => {

            let newType = types[types.length - 1]; 


            this.setState({

                selectedDates: [], 

                currentType: newType.id

            });

        }).catch(error => {

            //handle error

        });


    }}


>Create</button>

和onCreateClick函數返回無極其中reslove您收到新的類型,然后你處理它們在你的狀態組件。


如果您希望可以將此代碼更改為async\await,則與 promise 相同。


查看完整回答
反對 回復 2022-01-01
?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

我會返回類似布爾值的內容onCreateClick()并將其存儲在變量中。然后您可以輕松檢查該變量是否已設置。


this.state = {

   selectedDates: [Date], 

   currentType: null, 

}


handleOnClick = () => {

  const isHandled = this.props.onCreateClick(this.state.selectedDate)

  if(isHandled){

    let newType = this.props.types[this.props.types.length - 1]; 


    this.setState({

       selectedDates: [], 

       currentType: newType.id

    })

  }

}


<button type="button" onClick={() => this.handleOnClick()}>Create</button>


查看完整回答
反對 回復 2022-01-01
  • 2 回答
  • 0 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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