몇 가지 메시지가있는 방이 있습니다. 그래서이 모델은렌더링 방법은 2 번만 반응합니다.
{
createdAt: Date,
messages: [String]
}
내가
class Room extends React.Component {
constructor(props) {
super(props);
this.state = { room: {} };
}
componentDidMount() {
this.fetchRoom();
}
componentDidUpdate(prevProps) {
let oldId = prevProps.params.roomId
let newId = this.props.params.roomId
if (newId !== oldId) {
this.fetchRoom();
}
}
componentWillUnmount() {
this.ignoreLastFetch = true;
}
fetchRoom() {
if (!this.ignoreLastFetch) {
const roomId = this.props.params.roomId;
socket.emit('get room', roomId, room => {
this.setState({ room: room });
});
}
}
render() {
console.log(this.state.room.messages); // debug
const roomId = this.state.room._id;
return (
<div>
<h2>Id: {roomId}</h2>
<p>Created at: {this.state.room.createdAt}</p>
<h2>Messages</h2>
<Messages roomId={roomId} messages={this.state.room.messages} />
</div>
);
}
}
내 방을 페치 문제는 render()
모두가 내가 방을 인출 한 후 방 을 가져왔다 전에 , 소위 때문이다 2 건의 전화가 걸립니다.
빈 방을 보지 않아도 방을 가져올 때까지 render
번을 기다릴 수 있습니까?
<Messages roomId={roomId} messages={this.state.room.messages} />
을 사용하고 있기 때문에 메시지 배열이 비어있는 것으로 보입니다. render()
메소드에서 console.log(this.state.room.messages)
으로 디버깅하면 먼저 정의되지 않은 내용이 인쇄 된 다음 메시지 배열 (즉 2 건)이 인쇄됩니다.
반응이있을 때 렌더링은 구성 요소가 마운트 된 직후 (또는?)에 호출되고 setState를 호출 한 후에 호출됩니다. 그건 정상입니다. –