如何解决依赖数组警告在React时,变量是有条件的?



我正在做一个取回请求在useEffect钩子。这就是它的样子。

useEffect(() => {
// clear prev state
setUniqueValues([]);
setLoading(true);
// get unique values and set field values;
jwtAxios
.post(`${baseURL}/support/get_unique_values`, {
field: fieldName,
catalog_id: catalogID,
page,
category_values: props?.initialValues?.schema?.category,
})
.then((data) => {
setUniqueValues(data.data.unique_values);
setLoading(false);
setError(false);
})
.catch((err) => {
console.log(err);
setError(err);
});
}, [catalogID, fieldName, page]);

在post请求中,我想发送一个值(category_values),如果它存在,如果它带有props。所以我检查了?

但如果我不把它放在依赖数组中它会报错:

warning  React Hook useEffect has a missing dependency: 'props?.initialValues?.schema?.category'. Either include it or remove the dependency array  react-hooks/exhaustive-deps 

如果我像[catalogID, fieldName, page,props?. initialvalues ?.schema?]类别]

报错如下:

Line 100:8:   React Hook useEffect has a missing dependency: 'props.initialValues.schema.category'. Either include it or remove the dependency array    react-hooks/exhaustive-deps
Line 100:37:  React Hook useEffect has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked  react-hooks/exhaustive-deps

如果我没有在没有传入props的时候输入? s,它就会因为没有找到props而崩溃。

怎么解?谢谢。

您可以在调用useEffect之前计算类别

const category = props?.initialValues?.schema?.category;
useEffect(() => {
setUniqueValues([]);
setLoading(true);
jwtAxios
.post(`${baseURL}/support/get_unique_values`, {
field: fieldName,
catalog_id: catalogID,
page,
category_values: category,
})
...
}, [catalogID, fieldName, page, category]);

最新更新