【发布时间】:2017-03-12 00:43:30
【问题描述】:
我有一个房间,里面有一些消息。所以模型是
{
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() 都被称为before我取房间和after我取房间,所以它导致2个电话。
因为我不在乎看到一个空房间,所以我不能等到我把房间拿走后再开render吗?
似乎因为我使用的是<Messages roomId={roomId} messages={this.state.room.messages} />,它会发送一个空的消息数组。如果我使用console.log(this.state.room.messages) 在render() 方法中调试,它首先打印未定义,然后打印消息数组(即2 个调用)。
【问题讨论】:
-
在 react 中,render 会在你调用
setState之后(或者之前?)组件被安装之后立即调用。这是正常的。
标签: javascript node.js reactjs socket.io react-router