react/error-boundaries 正确性
功能
验证是否使用错误边界,而不是在 JSX 周围使用 try/catch 来处理子组件中的错误。
由 React Compiler 提供支持,该编译器每个文件运行一次,并与其他 React Compiler 规则共享。移植自 react-hooks/error-boundaries。
为什么这是不好的?
React 会延迟渲染组件——在 try 块中,子组件尚未完成渲染,因此 catch 永远无法捕获其错误;只有错误边界才能捕获这些错误。
示例
此规则的错误代码示例:
jsx
function Component(props) {
let el;
try {
el = <Child />;
} catch {
return null;
}
return el;
}此规则的正确代码示例:
jsx
function Component(props) {
return (
<ErrorBoundary fallback={null}>
<Child />
</ErrorBoundary>
);
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/error-boundaries": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/error-boundaries": "error",
},
});bash
oxlint --deny react/error-boundaries --react-plugin版本
此规则在 vnext 中添加。
