【问题标题】:React component will mount is not getting calledReact 组件将挂载没有被调用
【发布时间】:2017-07-17 06:20:47
【问题描述】:

我一直在使用 react 和 websockets 开发聊天应用程序,我的问题是方法

组件WillUnmount() 当状态改变和组件重新渲染时不会被调用。

我一直在尝试为聊天中的每条新消息添加“li”元素到我的 chatArea 组件中,并且一旦我选择另一个聊天,我想删除所有在其中呈现的“li”元素以前的聊天,为此我尝试了两件事,一是删除所有孩子,或者我正在改变状态。但是 componentWillUnmount 没有被调用。而且我无法删除 li 元素。

下面是我的代码

import React from 'react'

export default class ChatArea extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      currentUser: this.props.currentUser,
      selectedUser: this.props.selectedUser,
      messages: []
    }
    this.handleMessage = this.handleMessage.bind(this)
  }

  handleMessage (obj) {
    let messages = this.state.messages
    messages.push(obj)
    this.setState({
      messages: messages
    })
  }

  componentWillMount () {
    window.socket.on('show message', obj => {
      this.handleMessage(obj)
    })
  }

  componentDidMount () {
    window.socket.emit('join', {
      sender: this.state.currentUser,
      receiver: this.state.selectedUser
    })
  }

  componentWillUnmount () {
    console.log('something')
    const chatList = this.refs.chatList
    while (chatList.hasChildNodes()) {
      console.log('removing children', chatList.lastChild)
      chatList.removeChild(chatList.lastChild)
    }
orrrrrrrrrrrrrr
      this.setState({
        messages: []
      })
  }

  render () {
    console.log('chatARea state', this.state)
    let messages = this.state.messages
    let i = 0
    return (
      <div className='row chat-area'>
        <ul className='col m12' ref='chatList'>
          {messages.map(msg => <li key={i++}>{msg.sentBy.firstname + ': ' + msg.message}</li>)}
        </ul>
      </div>
    )
  }
}

module.exports = ChatArea

【问题讨论】:

  • componentWillUnmount 只有在 ChatArea 组件即将卸载时才会被触发。
  • 当您从没有消息列表的聊天窗口更改状态时,很可能会调用 componentWillUnmount。无论如何,您都不应该以这种方式删除节点。让反应来处理它 - 只需根据您所在的视图更改您的消息对象并呈现相应的聊天
  • 顺便说一句,您通常需要删除侦听器和其他东西,而不是 componentWillUnmount 中的节点。
  • componentWillUnmount() 在组件被卸载和销毁之前立即被调用。在此方法中执行任何必要的清理,例如使计时器无效、取消网络请求或清理在 componentDidMount 中创建的任何 DOM 元素
  • @Sudheer 下面是我的这个组件的构造函数constructor (props) { super(props) this.state = { currentUser: this.props.currentUser, selectedUser: this.props.selectedUser, messages: [] } this.handleMessage = this.handleMessage.bind(this) } 所以每次我得到新的道具时,状态都会改变并且组件再次渲染,此时我想清除消息[],所以它不会出现在其他聊天消息窗口中

标签: reactjs


【解决方案1】:

我找到了自己问题的答案,组件的状态没有改变,所以方法 componentWillMount() 没有被调用。

感谢大家的帮助

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 2022-06-12
    • 2020-06-18
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多