你好,我是reactjs的初学者。在这里,我试图将消息数组传递给一个名为Message-List的组件。我正在使用this.props.messages.map()这样做,但是我收到一条错误消息TypeError:无法读取未定义的属性“地图”。
import React, { Component } from "react";
import ChatKit from "@pusher/chatkit";
import MessageList from "./component/Message-List";
import RoomList from "./component/Room-List";
import MessageSend from "./component/Message-Send";
import CreateRoom from "./component/Create-Room";
import TypeMessage from "./component/Type-Message";
import "./App.css";
import { tokenUrl, instanceLocator } from "./config";
class App extends Component {
constructor() {
super();
this.state = [
{
messages: []
}
];
}
componentDidMount() {
const chatManager = new ChatKit.ChatManager({
instanceLocator,
userId: "1",
tokenProvider: new ChatKit.TokenProvider({
url: tokenUrl
})
});
chatManager.connect().then(currentUser => {
currentUser.subscribeToRoom({
roomId: 19379359,
hooks: {
onNewMessage: message => {
console.log("message:text ", message.text);
this.setState({
messages: [...this.state.messages, message]
});
}
}
});
});
}
render() {
return (
<div className="App">
<RoomList />
<MessageList messages={this.state.messages} />
<CreateRoom />
<TypeMessage />
<MessageSend />
</div>
);
}
}
export default App;
这是我的组件消息列表,我正在其中尝试从App.js导入messages数组,但是它引发了错误。
import React from "react";
class MessageList extends React.Component {
render() {
return (
<div className="message-list">
{this.props.message.map((messages, index) => {
return (
<div key={index} className="message">
<div className="message-username">{messages.userId}</div>
<div className="message-text">{messages.text}</div>
</div>
);
})}
</div>
);
}
}
export default MessageList;
答案 0 :(得分:3)
您的初始状态为数组。您需要更改对象
this.state = [
{
messages: []
}
];
将其更改为
this.state = {
messages: []
}