在方法render()
中,我使用this.state.objects.map(item, id)
conversationTemplate = this.state.objects.map(function (item, index) {
return (
<Panel eventKey={index}>
<h4> {item.msg_text} </h4>
<ReactMessageChat conversationId={item.pk}> {item.pk} </ReactMessageChat>
</Panel>
)
}
当新项目出现渲染重启时,子元素conversationId
中的道具ReactMessageChat
始终保持为循环中的第一个。
class ReactMessageChat extends React.Component {
constructor(props) {
super(props);
this.state = {
objects: [],
loaded: false,
};
this.addNewMsg = this.addNewMsg.bind(this);
this.subscribe = this.subscribe.bind(this);
}
subscribe() {
return centrifuge;
}
loadDataFromServer(conversationId) {
let self = this;
var url = '/api/support_messages/?msg_conversation=' + conversationId
...
}
addNewMsg(message) {
let self = this;
if (message.msg_conversation == self.props.conversationId) {
var newArray = self.state.objects;
newArray.push(message);
self.setState({objects: newArray});
}
}
componentDidMount() {
this.loadDataFromServer(this.props.conversationId);
this.subscribe();
}
render() {
let self = this;
var messagesTemplate;
if (self.state.objects.length > 0) {
let reversedObjects = self.state.objects.reverse();
messagesTemplate = reversedObjects.map(function (item, index) {
return (
<li className="list-group-item" key={index}>
{item.msg_text}</li>
)
})
}
答案 0 :(得分:0)
这是因为在不同的循环方法中你必须给出属性&#34; key&#34;重复元素。 https://facebook.github.io/react/docs/lists-and-keys.html