如何 运行 挂载上的 useEffect 引用具有空依赖项数组的道具?

How to run a useEffect on mount that references props with an empty dependency array?

我只想将 useEffect 用于 运行 组件挂载上的一个函数,但该函数引用了 props 并且 React 给出了关于将 props 添加到依赖项数组的警告 - 但如果我这样做,那么它将不会仅在组件安装上更长 运行。

与类:

componentWillMount() {
    if (!this.props.variableInitialized) {
        this.props.dispatchPageFunction({ page: 'dashboard' })
        this.props.history.push('/')
    } else {
        this.props.dispatchPageFunction({ page: 'this_page' })
    }
}

尝试使用 Hooks:

useEffect(() => {
    if (!props.variableInitialized) {
        dispatch({ type: 'CHANGE_PAGE', page: 'dashboard' }
        props.history.push('/')
    } else {
        dispatch({ type: 'CHANGE_PAGE', page: 'this_page' }
    }
}, [])

hook方式会抱怨缺少依赖dispatch(它的react-redux hook版本,useDispatch()),props.variableInitializedprops.history,但是如果我添加它们,它们将不再 运行 专门挂载(并以挂钩方式卸载)。

如何获得 useEffect 挂钩 运行 与之前使用 类 时相同的方式,而不会丢失依赖项警告?

useEffect(() => {
    if (!props.variableInitialized) {
        dispatch({ type: 'CHANGE_PAGE', page: 'dashboard' }
        props.history.push('/')
    } else {
        dispatch({ type: 'CHANGE_PAGE', page: 'this_page' }
   } 
//eslint-disable-next-line },[])

我添加到代码中的注释(//eslint-disable-next-line) 将消除您因缺少依赖项而收到的抱怨。

React 钩子仍在开发中。有可能 lint 并不完全习惯各种挂钩的使用。根据reactjs.org:

所以,我认为在这种情况下禁用 lint 没问题。

尝试使用以下语法:

const [someString, setSomeString] = useState('init string');

const onMount = useCallback(
  () => {
    console.log(someString);
  }, 
  [state]
);

useEffect(onMount, []);

这里发生的事情是您使用了封装在 useCallback 中的外部函数。 eslint 在搜索依赖项时会忽略此语法。

useCallback 使用依赖项在状态发生变化时更新函数。但是 useEffect 不使用任何依赖项,因此它不会在挂载后再次 运行。

实际将其作为 onMount 函数

因此在您的情况下,代码将如下所示:

const onMount = useCallback(
    () => {
        if (!props.variableInitialized) {
            dispatch({ type: 'CHANGE_PAGE', page: 'dashboard' }
            props.history.push('/')
        } else {
            dispatch({ type: 'CHANGE_PAGE', page: 'this_page' }
        }
    }, 
    [dispatch, props.variableInitialized, props.history]
);

useEffect(onMount, [])