2017-11-27 4 views
0

React에서 Rocket.Chat에 대한 간단한 채팅 클라이언트를 작성하는 중입니다.
메시지를 서버에 보내고 보낸 메시지를 메시지 목록에 표시 할 수 있습니다.
이제 클라이언트가 서버에서 마지막 메시지를 가져 와서 내 메시지 목록에 표시하려고합니다.
API 엔드 포인트는 https://rocket.chat/docs/developer-guides/rest-api/channels/history입니다.Rocketchat History in React

채팅 내역에 올바르게 표시되도록 MessageList.js 구성 요소에 구현하는 방법을 알고 싶습니다.

순간에 구성 요소의 내 코드 그게 전부 :

import React, {Component} from 'react' 
import PropTypes from 'prop-types' 

import Message from '../Message/Message' 
import './MessageList.css' 

class MessageList extends Component { 

    static propTypes = { 
     messages: PropTypes.arrayOf(PropTypes.object) 
    } 

    static defaultProps = { 
     messages: [], 
    } 

    componentDidMount =() => { 

     fetch('http://localhost:3000/api/v1/channels.history?roomId=drtWNMjAmKM86hnxp', { 
      method: 'GET', 
      headers: { 
       'X-Auth-Token': '0qZt4LEd2pWHdCcjxFA-yn9RdOMdKpLMJPC-ejFDUCj', 
       'X-User-Id': 'JTFuq3JpgchDJT3Wb', 
       'Content-Type': 'application/json', 
      } 
     }) 


     console.log("Component did mount") 

    } 

    componentDidUpdate =() => { 
     this.node.scrollTop = this.node.scrollHeight 

    } 

    render() { 
     return (
      <div className="MessageList" ref={(node) => (this.node = node)}> 
       {this.props.messages.map((message, i) => (
        <Message key={i} {...message} /> 
       ))} 
      </div> 
     ) 
    } 

} 

export default MessageList 

답변

1

그것을 쉽게는 응용 프로그램 구성 요소에서 데이터를 가져 오는 상태로 제공하고 메시지 목록에 아래로 밀어. 다음

// getting the Message History and set it to the State 
    axios.get(
     window.url+'channels.historyroomId='+window.roomId, 
     {headers: { 
      'X-Auth-Token' : window.authToken, 
      'X-User-Id' : window.userId, 
      'Content-Type' : 'application/json' 
     } 
     } 
    ) 

     .then(res => { 
      const messages = res.data.messages; 
      messages.reverse(); 
      this.setState({ messages }); 
     }); 

과 :

<MessageList messages={this.state.messages} />