简体   繁体   English

反应:当 state 更改时,ChildComponent 不会重新渲染

[英]React: ChildComponent not getting re-rendered when state changes

I am working on a simple chat application in React with messages stored in Redux Store.我正在使用存储在 Redux 存储中的消息在 React 中开发一个简单的聊天应用程序。 I am looping through the messages and rendering <Message /> in <MessageContainer /> .我正在遍历消息并在<MessageContainer />中呈现<Message /> > 。 Now I want to acknowledge the sender that the message has been seen by the receiver, for that I am listening to an event and changing the message object in redux, which leads to change the state of the <Message /> .现在我想确认发送方消息已被接收方看到,因为我正在侦听一个事件并更改 redux 中的消息 object,这导致更改<Message />的 Z9ED39E2EA931586B6A985A6942EF573E。 I am using getDerivedStateFromProps() in <Message /> and able to change the state, however the component is not getting updated.我在<Message />中使用getDerivedStateFromProps()并且能够更改 state,但是该组件没有得到更新。

class MessageContainer extends React.Component {
    render() {
     const {messages} = this.props;
     return messages.map(message => <Message key={message.id} {...message} />)
   }
}

class Message extends React.Component {
   constructor(props) {
     super(props);
     this.state = {
         isMessageSeen: props.isMessageSeen
       }
    }
   static getDerivedStateFromProps(props,state) {
      return {isMessageSeen: props.isMessageSeen}
   }
  render() {
   const {isMessageSeen} = this.state;
   <div>
    {isMessageSeen ? 'Message Seen' : 'Message Sent'}
   </div>
 }
}

why do any of that and just use props?为什么要这样做并且只使用道具?

class Message extends React.Component {
  render() {
   <div>
    {this.props.isMessageSeen ? 'Message Seen' : 'Message Sent'}
   </div>
  }
}

React will always re-render when props change当 props 改变时,React 总是会重新渲染

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM