如果道具改变,反应重新评估 useRef

React re-evaluate useRef if props change

一个子组件有一个依赖于父属性的 ref 数组。如果道具发生变化而不重新渲染我的子组件,我想更新参考列表。

const childComponent = (props) =>
{
  // the array of ref item list
  const itemsRef = Array.from({ length: props.menuItems.length }, a => 
  useRef(null));

  useLayoutEffect(()=>
  {
   // enter anim new item ref...

  },[props.menuItem])


  return <ul>
    {props.menuItems.map((el,i) => 
      <li 
        key{i} 
        ref={itemsRef[i]}
        children={el.name}
     >}
  </ul>

}

itemsRef 如果父更新通过 props 传递新的 menuItem 列表,则不会重新计算。

如何用钩子实现这个?

您正在破坏 Rules of Hooks 不要在循环、条件或嵌套函数中调用 Hooks

一个解决方案可能是使用 useRef 来声明一个 instance variable 这将是一个数组,并使用 ref callback 来填充该数组中的元素:

const childComponent = props => {
   const itemsRef = useRef([]);
   // you can access the elements with itemsRef.current[n]

   return (
     <ul>
        {props.menuItems.map((el,i) => 
          <li 
            key={i} 
            ref={el => itemsRef.current[i] = el}
            children={el.name}
          />
        }
    </ul>
  );
}

如果你不希望数组中有空值,你可以添加一个效果来保持数组长度与props.menuItems长度同步(效果将在after 裁判回调)

useEffect(() => {
  itemsRef.current = itemsRef.current.slice(0, props.menuItems.length);
}, [props.menuItems]);