0

在这里,我试图了解https://www.npmjs.com/package/react-native-gifted-chat此链接中提供的代码。但是在这里我无法理解为什么他们在 setState 函数中使用 2 _id (messages:[{_id:1, //code user:{ _id:2, //code }]) 并且他们正在编写 1 id (_id: 1 ) 在 render() 方法中。还有在 setState 函数中传递的 id 1 和 2 与在 render() 方法中给出的 id 之间有什么区别。

下面是代码片段:

从 'react' 导入 React 从 'react-native-gifted-chat' 导入 { GiftedChat }

class Example extends React.Component {
  state = {
    messages: [],
  }

  componentDidMount() {
    this.setState({
      messages: [
        {
          _id: 1,
          text: 'Hello developer',
          createdAt: new Date(),
          user: {
            _id: 2,
            name: 'React Native',
            avatar: 'https://placeimg.com/140/140/any',
          },
        },
      ],
    })
  }

  onSend(messages = []) {
    this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, messages),
    }))
  }

  render() {
    return (
      <GiftedChat
        messages={this.state.messages}
        onSend={messages => this.onSend(messages)}
        user={{
          _id: 1,
        }}
      />
    )
  }
}
4

1 回答 1

0

_id: 1是消息的 id,并且_id: 2是编写消息的用户的 id,这样GiftedChat就可以将消息与编写它的人绑定。

使用类似的逻辑,用户发送的每条消息都将与渲染函数中的 id 绑定。

于 2020-03-06T11:35:54.057 回答