学无先后,达者为师

网站首页 编程语言 正文

react props数据更改传到方法里进行渲染html,当父组件改变props改变传入函数参数没有改变

作者:有问题请评论我改 更新时间: 2022-04-05 编程语言

解决方法使用JSON.parse(JSON.stringify(variableObject))深拷贝一下需变动的数组,因为如果不拷贝map改变了数组(数组里的元素为引用类型),而react禁止改变props

  getOnlineData = (roommates, onlineRoommates) => {
    const newRoommates =JSON.parse(JSON.stringify(roommates))
    return (newRoommates.map(item => {
      onlineRoommates.map(element => {
        if (`${item.user_type}:${item.user_id}` === element.userId) {
          item.isOnline = true
          item.hasVideo = element.hasVideo
          item.hasAudio = element.hasAudio
        }
      })
      return this.renderItem(item)
    }))
  }
  render () {
    const { roommates, onlineRoommates } = this.props
 
    return (
      <div className={styles.container}>
        {this.getOnlineData(roommates, onlineRoommates)}
      </div>
    )
  }

原文链接:https://blog.csdn.net/qq_26889291/article/details/122825536

栏目分类
最近更新