首页 > 解决方案 > 使用 useRef 更新 props 更改的附加子项

问题描述

const A= (props) => {

  const {category,screen} = props

  const ref = useRef()

  useEffect(()=>{
    const script = document.createElement('script');
      script.src = "xyz.js"
      script.async = true;
      script.innerHTML = JSON.stringify({"width": 1100,
      "height": 512,
      "market": category
})
      ref.current.appendChild(script)
      return () => {ref.current.removeChild(script);} // not working
  },[category])

    return (
<div className="tradingview-widget-container" ref={ref}>
  <div className="tradingview-widget-container__widget"></div>
 
</div>
    )
}

export default A

我创建了这个组件,以便每当更改类别时,附加的子项将被替换为具有从 props(category) 传递的新“市场”值的脚本

它工作正常,但是删除子项不起作用,如果不使用它,它会不断地一次又一次地添加脚本,这使得组件多次出现并且不会自我更新

我该如何更新这个?

标签: javascripthtmlreactjs

解决方案


首先,永远不要createElement在 react 中使用 vanilla js 或 jquery。其次,useEffect 钩子有两个部分:

useEffect(()=>{
   
   // This part will run on component mount
   console.log("Component did mount")
   return  () => {
   
   // This part will run on component unmount 
   console.log("Component did unmount")
   }
} , [state] )

您不需要总是包含返回回调函数,但只有当您需要在组件上执行某些操作时才 unmount 。

在 react js 中你可以有多个 useEffects 。因此,您可能希望将另一个 useEffect 用于 [category] ​​的另一个条件。


推荐阅读