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

jan*_*nay 1 javascript reactjs react-hooks

我正在 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]);
Run Code Online (Sandbox Code Playgroud)

在发布请求中,我想发送一个值(category_values),如果它存在,如果它带有道具。所以我检查一下?

但如果我不将它放入依赖数组中,它会抱怨:

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

如果我添加它,如 [catalogID, fieldName, page,props?.initialValues?.schema?.category ]

它抱怨如下:

  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
Run Code Online (Sandbox Code Playgroud)

如果我在未传递道具时不放置 ?,它就会崩溃,因为它找不到道具。

我该如何解决?谢谢。

Oli*_*ssé 6

您可以在调用之前计算类别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]);
Run Code Online (Sandbox Code Playgroud)