ReactJS在状态内渲染项目数组

时间:2019-04-18 15:28:44

标签: javascript reactjs

我正在尝试呈现项目列表,但出现此错误:

Objects are not valid as a React child (found: [object MessageEvent]). If you meant to render a collection of children, use an array instead.
    in li (at Chat.js:51)
    in ul (at Chat.js:47)
    in div (at Chat.js:70)
    in div (at Chat.js:63)
    in Chat (created by Context.Consumer)
    in Route (created by withRouter(Chat))
    in withRouter(Chat) (created by Context.Consumer)
    in Route (at App.js:14)
    in Switch (at App.js:12)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:11)
    in App (at src/index.js:12)
    in Router (created by BrowserRouter)
    in BrowserRouter (at src/index.js:11)

messages数组由连接的WebSocket填充。 这就是我所做的:

import React, { Component } from 'react';
import './Home.css';
import { withRouter } from 'react-router-dom';

class Chat extends Component {

    constructor() {
        super();

        this.state = {
            username: '',
            ws: '',
            message: '',
            messages: [],
        }

        this.handleMessageChanged = this.handleMessageChanged.bind(this);
        this.sendMessage = this.sendMessage.bind(this);
    }

    componentDidMount() {
        const self = this;
        this.setState({
            username: this.props.history.location.state.username,
            ws: new WebSocket(`ws://localhost:3001?username=${ this.props.history.location.state.username }`),
        }, () => {
            this.state.ws.addEventListener('message', (message) => {
                self.setState({ messages: [...self.state.messages, message] });
            });
        });
    }

    handleMessageChanged(event) {
        this.setState({ message: event.target.value });
    }

    sendMessage(event) {
        if (event.key === 'Enter') {
            this.state.ws.send(this.state.message);
            this.setState({ message: '' });
        }
    }

    renderMessages() {
        let messages = this.state.messages;
        return (
            <ul>
                {
                    messages.map((message, index) => {
                        return (
                            <li key={index}>
                                {message}
                            </li>
                        );
                    })
                }
            </ul>
        );
    }

    render() {
        return (
        <div className="Chat">
            <header className="App-body">
            <p>
                <code>ChatApp</code>
            </p>
            </header>

            <div className="container App-body">
                {this.renderMessages()}
                <input className="form-control form-control-lg message-box" value={this.state.message} onKeyDown={this.sendMessage} onChange={this.handleMessageChanged} type="text" placeholder="Enter your message here" />
            </div>

        </div>
        );
    }
}

export default withRouter(Chat);

您知道我为什么会收到此错误吗?

我还尝试通过以下方式调用他的renderMessages函数:

{this.renderMessages}

但是我得到了这个错误:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
    in div (at Chat.js:70)
    in div (at Chat.js:63)
    in Chat (created by Context.Consumer)
    in Route (created by withRouter(Chat))
    in withRouter(Chat) (created by Context.Consumer)
    in Route (at App.js:14)
    in Switch (at App.js:12)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:11)
    in App (at src/index.js:12)
    in Router (created by BrowserRouter)
    in BrowserRouter (at src/index.js:11)

2 个答案:

答案 0 :(得分:2)

这意味着{message}函数中的renderMessages是一个对象。对这个值做一些console.log。您可能要从message中选择一个特定字段。

答案 1 :(得分:2)

您无法在

中渲染对象message
<li key={index}>{message}</li>

替换
<li key={index}>{JSON.stringify(message)}</li>

或使用消息内容呈现<div>

<li key={index}>
  <div>{message.prop}</div> <!-- I don't know what properties your object has -->
</li>