简体   繁体   English

聊天中的消息顺序React

[英]Order of messages in chat React

I am going back to programming after some time. 我会在一段时间后回到编程。 I wrote chatApp once. 我写了一次chatApp。 Now I want to change something there. 现在我想在那里改变一些东西。 For now, new messages on chat shows on the top of messages list. 目前,聊天新消息显示在消息列表的顶部。 I want make it on the bottom. 我想把它放在底部。 I guess that I have to do something with state update. 我想我必须做一些状态更新。 Please show me where it was. 请告诉我它在哪里。

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>
    );

} }

just change this handler. 只需更改此处理程序。

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

in order to append the new message to the bottom. 为了将新消息附加到底部。

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

you can reverse the array of messages and pass it to the MessagesList 您可以反转消息数组并将其传递给MessagesList

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

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

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