【问题标题】:Getting Rocketchat History in React在 React 中获取 Rocketchat 历史记录
【发布时间】:2018-05-10 12:24:25
【问题描述】:

我正在用 React 为 Rocket.Chat 写一个简单的聊天客户端。
目前可以向服务器发送消息并在消息列表中显示已发送的消息。
现在我希望客户端从服务器获取最后一条消息并将其显示在我的消息列表中。
为此有一个 API 端点:https://rocket.chat/docs/developer-guides/rest-api/channels/history

我想知道如何在我的 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

【问题讨论】:

    标签: reactjs rest fetch-api rocket.chat


    【解决方案1】:

    更容易在 App 组件中获取数据,将其放入状态并将其推送到消息列表。

    // 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} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2013-08-02
      相关资源
      最近更新 更多