Can't use useRef as componentDidUpdate replacement

删除回忆录丶 提交于 2020-12-15 05:45:47

问题


Error

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)

I have a functional component and trying to take advantage of hooks to use componentDidUpdate, in my onSubmit function I fire a dispatch to call and API, and I need to see what is the resulting payload of that API, which is stored in redux. But I get the error above?

I found this answer which said to use useRef Equivalent to componentDidUpdate using React hooks


回答1:


useRef is a React hook. Change to:

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



回答2:


You should access your ref using mounted.current. Since you are not initializing it a value, it will return undefined.

If you are assigning your ref to a JSX element, you will not be able to access it until the DOM has loaded. In that case, I would suggest using the useLayoutEffect hook, since it will not run until the DOM has loaded.



来源:https://stackoverflow.com/questions/65040152/cant-use-useref-as-componentdidupdate-replacement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!