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

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

React:檢查 props 是否未定義

React:檢查 props 是否未定義

郎朗坤 2023-10-14 19:17:46
如果 prop 未定義,我想在 componentDidUpdate 中執行一些操作,但是,我不能,因為我剛剛收到錯誤Cannot read property 'serial' of undefined。有辦法解決這個問題嗎?這就是我累的,但它不起作用 - 我收到錯誤:componentDidUpdate(prevProps) {    if (typeof this.props.location.state.serial == "undefined"){const database = db.ref().child("Devices/" + prevProps.location.state.serial);...提前致謝!
查看完整描述

1 回答

?
慕婉清6462132

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

location首先,您應該對和對象進行測試location.state,因為它們可能是undefined因為在狀態或父組件的 props 中進行任何更新后立即調用此方法。你應該這樣做:

componentDidUpdate(prevProps)?{
????if?(this.props.location?&&?this.props.location.state?&&??typeof?this.props.location.state.serial?===?"undefined"){const?database?=?db.ref().child("Devices/"?+?prevProps.location.state.serial);
...

或者,如果您想利用新的 EcmaScript 語法:

componentDidUpdate(prevProps)?{
????if?(typeof?this.props.location?.state?.serial?===?"undefined"){const?database?=?db.ref().child("Devices/"?+?prevProps.location.state.serial);
...


查看完整回答
反對 回復 2023-10-14
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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