![](/img/trans.png)
[英]How do I use setNativeProps in Functional Components? React-native
[英]How can I make use of Error boundaries in functional React components?
從 v16.2.0 開始,無法將功能組件轉變為錯誤邊界。
React 文檔對此很清楚,盡管您可以隨意多次重用它們:
componentDidCatch()
方法的工作方式類似於 JavaScriptcatch {}
塊,但用於組件。 只有類組件可以是錯誤邊界。 在實踐中,大多數時候您希望聲明一次錯誤邊界組件並在整個應用程序中使用它。
還要記住, try/catch
塊並不適用於所有情況。
如果層次結構深處的組件嘗試更新並失敗,則其中一個父級中的try/catch
塊將不起作用——因為它不一定與子級一起更新。
有一個實現可以處理功能組件不存在的功能,例如componentDidCatch
和deriveStateFromError
。
據作者介紹,它基於 React.memo()。
提議的解決方案受到新的 React.memo() API 的極大啟發。
import Catch from "./functional-error-boundary"
type Props = {
children: React.ReactNode
}
const MyErrorBoundary = Catch(function MyErrorBoundary(props: Props, error?: Error) {
if (error) {
return (
<div className="error-screen">
<h2>An error has occured</h2>
<h4>{error.message}</h4>
</div>
)
} else {
return <React.Fragment>{props.children}</React.Fragment>
}
})
參考和API 在這里
如前所述,React 團隊還沒有實現等效的鈎子,也沒有發布鈎子實現的時間表。
npm 上的一些第三方包實現了錯誤邊界掛鈎。 我發布了react-use-error-boundary ,試圖從 Preact 重新創建一個類似於 useErrorBoundary的 API:
import { withErrorBoundary, useErrorBoundary } from "react-use-error-boundary";
const App = withErrorBoundary(({ children }) => {
const [error, resetError] = useErrorBoundary(
// You can optionally log the error to an error reporting service
(error, errorInfo) => logErrorToMyService(error, errorInfo)
);
if (error) {
return (
<div>
<p>{error.message}</p>
<button onClick={resetError}>Try again</button>
</div>
);
}
return <div>{children}</div>;
});
官方 React 團隊沒有為功能組件提供錯誤邊界支持。 我們可以使用 npm 包實現功能組件的錯誤邊界。 https://www.npmjs.com/package/react-error-boundary
我所做的是創建自定義class component
並將我的functional/class
組件包裝在它需要的地方。 這是我的自定義類組件的樣子:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {error: ""};
}
componentDidCatch(error) {
this.setState({error: `${error.name}: ${error.message}`});
}
render() {
const {error} = this.state;
if (error) {
return (
<div>{error}</div>
);
} else {
return <>{this.props.children}</>;
}
}
}
並像這樣使用它我的functional/class
組件:
<ErrorBoundary key={uniqueKey}>
<FuncationalOrChildComponent {...props} />
</ErrorBoundary>
PS:像往常一樣, key 屬性非常重要,因為如果您有動態子元素,它將確保重新渲染ErrorBoundary
組件。
官方 React 團隊尚未為功能組件提供錯誤邊界鈎子。 但是你可以使用第三方包來實現功能組件的錯誤邊界。 https://www.npmjs.com/package/react-error-boundary但它仍然有一些問題所以我建議不要使用它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.