首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >反应,用道具循环

反应,用道具循环
EN

Stack Overflow用户
提问于 2017-09-02 13:51:00
回答 1查看 154关注 0票数 1

在方法render()中,我用this.state.objects.map(item, id)调用子元素的循环

代码语言:javascript
复制
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始终作为循环中的第一个。

代码语言:javascript
复制
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>
            )
        })
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-02 18:05:02

这是因为在不同的循环方法中,必须将属性"key“给重复元素。https://facebook.github.io/react/docs/lists-and-keys.html

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46014489

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档