聊天中消息的顺序React

时间:2019-01-30 16:06:39

标签: javascript reactjs chat

一段时间后,我将重新编程。我曾经写过chatApp。现在,我想在那里更改某些内容。目前,聊天列表中的新消息显示在消息列表的顶部。我要放在底部。我想我必须对状态更新做些事情。请告诉我它在哪里。

class App extends Component {
constructor(props) {
    super(props);
    this.state = {users: [], messages: [], text: '', name: ''};
}

componentDidMount() {
    socket.on('message', message => this.messageReceive(message));
    socket.on('update', ({users}) => this.chatUpdate(users));
}

messageReceive(message) {
    const messages = [message, ...this.state.messages];
    this.setState({messages});
}

chatUpdate(users) {
    this.setState({users});
}

handleMessageSubmit(message) {
    const messages = [message, ...this.state.messages];
    this.setState({messages});
    socket.emit('message', message);
}

handleUserSubmit(name) {
    this.setState({name});
    socket.emit('join', name);
}

render() {
    return this.state.name !== '' ? (
        this.renderLayout()
    ) : this.renderUserForm()
}

renderLayout() {
    return (
        <div className={styles.App}>
            <div className={styles.AppHeader}>
                <div className={styles.AppTitle}>
                    ChatApp
                </div>
                <div className={styles.AppRoom}>
                    App room
                </div>
            </div>
            <div className={styles.AppBody}>
                <UsersList
                    users={this.state.users}
                />
                <div className={styles.MessageWrapper}>
                    <MessageList
                        messages={this.state.messages}
                    />
                    <MessageForm
                        onMessageSubmit={message => this.handleMessageSubmit(message)}
                        name={this.state.name}
                    />
                </div>
            </div>
        </div>
    );

}

2 个答案:

答案 0 :(得分:3)

只需更改此处理程序即可。

messageReceive(message) {
    const messages = [message, ...this.state.messages];
    this.setState({messages});
}

为了将新消息添加到底部。

messageReceive(message) {
    const messages = [...this.state.messages, message];
    this.setState({messages});
}

答案 1 :(得分:1)

您可以反转消息数组并将其传递给MessagesList

<MessageList
  messages={this.state.messages.reverse()}
/>