我已经有了这样一个状态:
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})
我怎么能做到呢?或者我需要从零开始设置一个新的状态
根据React文档(webarchive来源):
状态应包含组件的事件处理程序可能更改以触发UI更新的数据。在真实的应用程序中,这些数据往往非常小,并且是JSON可序列化的。构建有状态组件时,考虑其状态的最小可能表示,并且只将这些属性存储在this.state
中。内部的渲染()
只需根据此状态计算任何其他所需的信息。您会发现,以这种方式思考和编写应用程序往往会导致最正确的应用程序,因为向状态添加冗余或计算值意味着您需要显式地保持它们同步,而不是依赖React为您计算它们。
这个。状态
应仅包含表示用户界面状态所需的最小数据量。因此,它不应包含:
render()
中进行所有计算,则更容易确保用户界面的一致性。例如,如果您有一个处于状态的列表项数组,并且希望将计数呈现为字符串,只需呈现this即可。状态清单项目。在render()
方法中设置长度“列出项目”
,而不是将其存储在状态李>在您的情况下,将html移动到渲染函数中。然后在您的状态中存储一个条件或数据,该条件或数据将用于触发向html中添加另一个div,方法是有条件地呈现一些html,或者向html中的数组添加另一个div。基于向状态添加更多数据的映射函数。
例子:
Class Example render React.Component{
state = {
comments: [
{ message:"comment 1", id: 1, timeStamp: "" },
{ message:"comment 2", id: 2, timeStamp: "" },
{ message:"comment 3", id: 3, timeStamp: "" }
]
}
componentDidMount = () => {
//update data from api...
.then(data => this.setState({ comments: data }))
}
render(){
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>
)
}
})
}
}
我认为以组件状态存储jsx组件不是一个好主意。我认为您应该只保存呈现组件所需状态的数据。
如果您真的想将jsx存储在状态中,为什么不将您的会话属性定义为数组?然后您将能够向其添加新组件。
this.setState({
conversation: [
(<div>first</div)
]
});
const currentConversation = state.conversation;
currentConversation.push((<div>new div</div>));
this.setState({conversation: currentConversation})
但最好只存储数据即第一和新div