[英]Is there a way to universally cancel all calls to setstate on any unmounted component or to hide the errors produced by attempting it?
我首先要說的是我實際上並沒有試圖隱藏錯誤,我會修復它們,但我需要知道它是否可行。
我正在用.net后端重寫一個反應項目,從框架轉換到核心。
我有兩個組件(原始項目中的一個和新項目中的一個)基本相同。
它們是一種模式,當打開時,收集並顯示文章。 如果模式已關閉,則組件將被卸載,如果它在文章數據返回之前(使用fetch),則它當前是錯誤的,因為它正在嘗試更新未安裝組件的狀態。
此行為是預期的。
在新項目中,我正要添加一個AbortController以在需要時中止提取調用,但我注意到在舊項目中,在收集數據之前關閉模式時,不會給我一個錯誤。 組件卸載,然后狀態更新,但由於某種原因我沒有收到錯誤。 沒有'isMounted'變量跟蹤掛載狀態,也沒有中止控制器。
我在每個相關方法中添加了控制台日志,以確保在狀態更新之前卸載它。
有什么東西可以隱藏這些錯誤嗎? 或者阻止一起行動?
兩個項目都使用react 16,但舊項目在外部引用( https://unpkg.com/react@16/umd/react.development.js ),新項目通過npm(^ 16.8.6)提供。
這是來自舊項目的相關代碼,因為這是錯誤未生成的(新項目幾乎相同)
componentDidMount() {
fetch(`{url to get article}`,
{ credentials: "include", headers: { accept: "application/json" } })
.then(res => res.json())
.then(gatheredData => this.setState({ gatheredData }))
}
沒有componentWillUnmount。
當我無法從組件中刪除調用時,我就是這樣做的
componentDidMount() {
this.mounted=true
fetch(`{url to get article}`,
{ credentials: "include", headers: { accept: "application/json" } })
.then(res => res.json())
.then(gatheredData => {
if (this.mounted) {
this.setState({ gatheredData })
}
})
}
componentWillUnmount() {
this.mounted=false
}
我發現在舊項目中,原始作者以一種方式編寫它(即使它被指定在開發中使用完整版本),它總是從外部導入反應的縮小生產版本。 這就是導致錯誤無法顯示的原因。 當我修復它時,控制台像聖誕樹一樣點亮。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.