我正在建立一个反应聊天应用程序,这就是我的问题;我正在尝试创建一个名为msgSntInRm
的{{1}}元素的属性,实际上跟踪创建时发送消息的房间。但是使用下面的代码,即使在发送/创建消息之后,属性也会根据所选房间的状态而变化。
p
我明白为什么会这样。这是我的构造函数:
<div className='chatDisplay'>
{
this.state.testArr.map((msg, pos, array) =>
<p className='testArr'
testArrPos={pos}
msgSntInRm={this.state.currentRoom}>
{msg}
</p>
)
}
</div>
我只是不确定如何解决这个问题。 Here is a GIST of the code
我需要将代码class RoomList extends Component {
constructor(props) {
super(props);
this.state = {
rooms: [],
display: 'none',
displayRoom: 'none',
newRoomName: 'New room',
currentRoom: '',
testArr: [],
msgSntIn: ''
};
this.roomsRef = this.props.firebase.database().ref('rooms');
}
替换为跟踪创建消息的房间的内容,并且一旦我离开房间或创建新消息,它就无法再次更改。
答案 0 :(得分:1)
我认为msgSntIn
不应直接放在RoomList
组件状态中,而应放在this.state.testArr
的对象元素中。
你可以像这样重构你的submitTweet函数的setState:
this.setState((prevState) => {
return {
testArr: prevState.testArr.concat({
content: content,
msgSntIn: roomNo
})
}
});
另请注意,只要您想修改组件的状态,就应该使用setState。如果你需要先前的状态,你可以传递setState
一个回调,第一个参数将是前一个状态,第二个参数是前一个状态。
您的邮件组件可能如下所示:
const Message = (props) => {
return (<p msgSntIn={props.msgSntIn} key={props.key}>{props.content}</p>)
}
在渲染功能中,您可以执行以下操作:
this.state.rooms.map((room, indexPos ) => {
return (<Message msgSntIn={room.msgSntIn} content={room.content} key={props.key} />
})
答案 1 :(得分:1)
您应该将消息与房间关联起来,使用州内的当前房间将无济于事。
而不是将消息存储为字符串数组,存储一个对象数组,每条消息将如下:
{ msg: 'bla bla', room: 'room1', // other properties }
这样,当您迭代邮件时,您可以根据邮件对象数据指定邮件发送到哪个房间。