我有一个可重用的自定义输入组件,它可能会也可能不会在 Formik 上下文中使用(即在 Formik 表单中或通常在 Formik 表单之外)。行为需要相应地有所不同。我需要确定该组件中的模式。有一个名为 useFormikContext()
的钩子(Hook),如果不适用,它将抛出错误。但当我这么做的时候
try {
const { values, setFieldValue } = useFormikContext();
}
catch (error) {
alert('NOT in the Formik Context');
}
finally {
alert ('End');
}
我明白了
Line 17:43: React Hook "useFormikContext" is called conditionally.
React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks
那么有没有一种方法可以清楚地确定我是否可以应用该钩子(Hook)?
最佳答案
只需不要从钩子(Hook)中解构并检查传入值是否未定义
或不执行您的逻辑,如下所示:-
const formik = useFormikContext();
if (!formik) {
alert("NOT in the Formik Context");
} else {
alert("In the formik context");
}
这是代码和框:-
尽管我建议在 if/else 条件中显示抛出自定义错误,并在 错误边界 中捕获此错误,然后使用后备组件来显示错误,而不是使用 alert
如果它是一个需要描绘的 UI 事物。否则,请完全跳过错误边界并发出警报,因为 console.warn
日志更适合此操作。
关于javascript - "React Hook is called conditionally": How to check for optional contexts in a component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67623006/