【问题标题】:Can't use useRef as componentDidUpdate replacement不能使用 useRef 作为 componentDidUpdate 替换
【发布时间】:2021-03-10 09:39:43
【问题描述】:

错误

Uncaught TypeError: Object(...) is not a function

import { useSelector, useDispatch, useRef } from 'react-redux'

const mounted = useRef();

    useEffect(() => {
        console.log('mounted', mounted)
        console.log('useEffect props:', props)

我有一个功能组件并试图利用钩子来使用 componentDidUpdate,在我的 onSubmit 函数中我触发了一个调度来调用和 API,我需要查看该 API 的结果有效负载是什么,它存储在还原。但是我得到了上面的错误?

我发现这个答案说使用 useRef Equivalent to componentDidUpdate using React hooks

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    useRef 是一个 React 钩子。改为:

    import React, { useRef } from 'react';
    import { useSelector, useDispatch } from 'react-redux';
    

    【讨论】:

      【解决方案2】:

      您应该使用mounted.current 访问您的参考。由于您没有将其初始化为值,因此它将返回 undefined

      如果您将 ref 分配给 JSX 元素,则在 DOM 加载之前您将无法访问它。在这种情况下,我建议使用 useLayoutEffect 钩子,因为它在 DOM 加载之前不会运行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-04
        • 1970-01-01
        • 2012-09-18
        • 1970-01-01
        • 2020-11-06
        • 2017-07-31
        相关资源
        最近更新 更多