How to rerender when refs change

南笙酒味 提交于 2021-01-26 21:07:31

问题


Code:

import DrawControl from "react-mapbox-gl-draw";

export default function MapboxGLMap() {
    let drawControl = null
    return(
      <DrawControl ref={DrawControl => {drawControl = DrawControl}}/>
    )
}

I want to load data when the drawControl not null. I check the document that may use callback ref.

So, how do I listen the drawControl changes and load data?


回答1:


If you want to trigger a re-render after the ref changes, you must use useState instead of useRef. Only that way can you ensure that the component will re-render. E.g.:

function Component() {
  const [ref, setRef] = useState();

  return <div ref={newRef => setRef(newRef)} />
}

As described under useRef documentation:

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

It may sometimes be better to store whatever value you are getting from the DOM node, as suggested here, instead of storing the node itself.




回答2:


useCallback could listen the ref changed

export default function MapboxGLMap() {
    const drawControlRef = useCallback(node => {
      if (node !== null) {
        //fetch(...)   load data
      }
    },[]);

    return(
      <DrawControl ref={drawControlRef }/>
    )
}



回答3:


You can use a callback function that useEffect base on the change in useRef

   function useEffectOnce(cb) {

        const didRun = useRef(false);
        useEffect(() => {
            if(!didRun.current) {
                cb();
                didRun.current = true
            }
        })
    }


来源:https://stackoverflow.com/questions/59600572/how-to-rerender-when-refs-change

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