javascript - 使用 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) 传递的新“市场”值的脚本
它工作正常,但是删除子项不起作用,如果不使用它,它会不断地一次又一次地添加脚本,这使得组件多次出现并且不会自我更新
我该如何更新这个?
解决方案
首先,永远不要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] 的另一个条件。
推荐阅读
- database-design - 如何设计架构以读取同时更新的巨大数据库表
- sql - 如何为上夜班的员工安排退房时间
- php - 如何限制回声字段中的单词
- java - 将时间表详细信息保存在 sql 表中的多行中
- asp.net-mvc - 你如何在asp.net mvc中添加一个部分
- android - 如何使用 SQLiteOpenHelper 类从 sqlite 数据库中删除项目
- asp.net-core - 如何使用 Postman 调用 Identity Server 4 进行登录
- fiware - Fiware-Orion 中的实体 ID 无效
- bash - Bash:查看表格的第一列,如果行中的元素相同,则合并行
- ethereum - 如何为单笔交易设置不同的签名者和汽油支付者