日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

react調(diào)用MATERIAL-UI的組件中使用componentWillReceiveProps或shouldComponentUpdate報錯Missing semicolon.

作者:LangForOne 更新時間: 2023-10-27 編程語言

在學(xué)習(xí)react做小項目時遇到的bug,調(diào)用MATERIAL-UI的警告彈出框組件時使用componentWillReceiveProps報了如下錯誤:

起因是想讓props里的id發(fā)生變化時更新localStorage里的‘id’。

報錯的missing?semicolon的字面意思是“丟失分號”,但標(biāo)點符號我都寫對了,錯誤顯然沒有這么簡單。

后來發(fā)現(xiàn)MATERIAL-UI里的組件都是Function Component,也就是函數(shù)式組件,而函數(shù)式組件是沒有生命周期的,故不能使用類組件的更新期生命周期函數(shù)?componentWillReceiveProps。

解決辦法:用useEffect來代替componentWillReceiveProps實現(xiàn)監(jiān)聽更新

①、在組件的頭部引入useEffect

import React, {useEffect} from 'react'

?②、調(diào)用useEffect,第一個參數(shù)為當(dāng)監(jiān)聽的對象發(fā)生更新改變時所執(zhí)行的函數(shù);第二個參數(shù)是數(shù)組,數(shù)組內(nèi)部的元素則為需要監(jiān)聽的對象。

    useEffect(()=>{
        if (localStorage.getItem('item') === null) {
            setItem(0);
        } else {
            setItem(localStorage.getItem('item'));
        }
    }, [props.item])

這樣就能在函數(shù)式組件中實現(xiàn)生命周期的更新期啦

原文鏈接:https://blog.csdn.net/vvv3171071/article/details/119461001

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新