React Native Flatlist在数据更新时多次呈现相同的项目

时间:2018-06-11 04:39:20

标签: javascript react-native react-native-flatlist

当数据更新时,react native flatlist组件呈现与数据列表相同的项目。这是一个聊天应用程序。当用户单击发送按钮时,this.state.messages会更新并导致平面列表重新呈现。但是,当它重新渲染时,所有组件都呈现相同。

Chat.js



this.produtos=produtos;




ChatBubble.js



import React, { Component } from 'react';
import { View, FlatList } from 'react-native';
import { connect } from 'react-redux';
import { ChatBubble, Input } from './';

import { Header } from '../header';

class Chat extends Component {
  state={
    messages: [],
  };

  componentWillMount() {
    this.setState({
      messages: [
        {
          text: this.props.navigation.state.params.chat.lastMessage,
          direction: 'left',
          timeStamp: new Date().getTime(),
          id: '666',
          user: {
            displayName: this.props.navigation.state.params.chat.displayName,
          },
        }, {
          text: 'Thanks Nick!',
          timeStamp: new Date().getTime(),
          direction: 'right',
          id: '589',
          user: {
            displayName: 'You',
          },
        },
      ],
    });
  }

  onSend = (message) => {
    const messageData = {
      text: message,
      timeStamp: new Date().getTime(),
      direction: 'right',
      id: Math.random(1000).toString(),
      user: {
        displayName: 'You',
      },
    };
    if (message !== '') {
      this.setState({
        messages: this.state.messages.concat([messageData]),
      });
    }
    setTimeout(() => this.list.scrollToEnd(), 200);
  }

  renderMessages = ({ item }) => {
    return <ChatBubble message={item} />;
  }

  render() {
    return (
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <Header title={this.props.navigation.state.params.chat.displayName} />
        <FlatList
          keyboardShouldPersistTaps='always'
          data={this.state.messages}
          contentContainerStyle={{ backgroundColor: 'white', justifyContent: 'flex-end', flexGrow: 1 }}
          keyExtractor={message => message.id}
          renderItem={this.renderMessages}
          ref={(ref) => { this.list = ref; }}
        />
        <Input onPress={this.onSend} />
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  let user;
  if (state.user.user) {
    user = state.user.user;
  }
  return { user };
};

export default connect(mapStateToProps)(Chat);
&#13;
&#13;
&#13;

The behaviour i should get

The behaviour i currently receive

1 个答案:

答案 0 :(得分:0)

根据你在问题中提到的代码,问题似乎是在追加new时没有保留前一个数组元素的状态。

const messages = [...this.state.messages,messageData] //

this.state.messages视为数组保持supposed data,并将messageData视为数组的单个元素。

this.setState({ messages:messages  });