问题描述
我已经对此有状态:
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.
Now I would like to update it with new information. So add another div to it.
类似的东西:
this.setState({conversation: previousConversation + new div})
我该怎么办?或者我需要从零开始设置新状态
How can I do it? Or I need to set a new state from zero
推荐答案
我认为以组件状态存储jsx组件不是一个好主意.我认为您应该只以呈现组件所需的状态保存数据.
I don't think it's a good idea to store jsx components in the state of a component. I think you should only save the data in the state needed to render the component.
如果您真的想在状态中存储jsx,为什么不将对话"属性定义为数组?然后,您可以向其中添加新组件.
If you really want to store jsx in the state, why won't you define your 'conversation' property as array? Then you'll be able to add new components to it.
this.setState({
conversation: [
(<div>first</div)
]
});
const currentConversation = state.conversation;
currentConversation.push((<div>new div</div>));
this.setState({conversation: currentConversation})
但是最好只存储数据,例如"first"和"new div"
But better to only store the data ie 'first' and 'new div'
这篇关于将元素添加到状态React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!