我呈现一个表单和一个列表。在初始加载时效果很好:
<UsersList users={this.state.users} /> <SendMessageForm sendMessage={this.addMessage} />
但是,当提交SendMessageForm时,this.state.users
失去了它的值,并且出现了错误Cannot read property 'map' of undefined
。
这是SendMessageForm:
export default class SendMessageForm extends React.Component {
constructor() {
super();
this.state = {
message: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
message: e.target.value
});
}
handleSubmit(e) {
e.preventDefault();
this.props.sendMessage(this.state.message);
this.setState({
message: ''
});
}
render() {
return (
<div id="MessageField">
<form
onSubmit={this.handleSubmit}
className="send-message-form">
<input
onChange={this.handleChange}
value={this.state.message}
placeholder="Type your message and hit ENTER"
type="text"
/>
</form>
</div>
);
}
}
这是用户列表:
import React, { Component } from 'react';
class UsersList extends Component {
render() {
return (
<div id="UList">
<ul className="users-list">
{this.props.users.map((user, index) => {
return (
<li key={index}>
<span>{user}</span>
</li>
);
})}
</ul>
</div>
);
}
}
export default UsersList;
您能帮助我了解状态变量用户如何失去其价值吗?
编辑:
将消息添加到MessageList。 MessageList可以正常工作,问题在于UsersList。顺便说一下,我正在使用Chatkit库。
addMessage(text) {
this.state.currentUser.sendMessage({
text,
roomId: this.state.roomId.toString()
})
.catch(error => console.error('error', error));
}