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

學無先后,達者為師

網站首頁 編程語言 正文

react調用MATERIAL-UI的組件中使用componentWillReceiveProps或shouldComponentUpdate報錯Missing semicolon.

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

在學習react做小項目時遇到的bug,調用MATERIAL-UI的警告彈出框組件時使用componentWillReceiveProps報了如下錯誤:

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

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

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

解決辦法:用useEffect來代替componentWillReceiveProps實現監聽更新

①、在組件的頭部引入useEffect

import React, {useEffect} from 'react'

?②、調用useEffect,第一個參數為當監聽的對象發生更新改變時所執行的函數;第二個參數是數組,數組內部的元素則為需要監聽的對象。

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

這樣就能在函數式組件中實現生命周期的更新期啦

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

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