我已经有了一个状态:
this.setState({ conversation: ( <div> {conversation.map(element => { if (element.id === this.props.id) { return( <div className="row msg_container base_sent"> <div className="col-md-10 col-xs-10"> <div className="messages msg_sent"> <p>{element.message}</p> </div> </div> </div> ) } else { return( <div className="row msg_container base_receive"> <div className="col-md-10 col-xs-10"> <div className="messages msg_receive"> <p>{element.message}</p> </div> </div> </div> ) } })} </div> ) })
现在,我想用新信息对其进行更新。因此,向其添加另一个div。
像这样:
this.setState({conversation: previousConversation + new div})
我该怎么做?或者我需要从零开始设置新状态
我认为以组件状态存储jsx组件不是一个好主意。我认为您应该仅以呈现组件所需的状态保存数据。
如果您真的想在状态中存储jsx,为什么不将“对话”属性定义为数组?然后,您可以向其中添加新组件。
this.setState({ conversation: [ (<div>first</div) ] }); const currentConversation = state.conversation; currentConversation.push((<div>new div</div>)); this.setState({conversation: currentConversation})
但是最好只存储数据,例如“ first”和“ new div”