javascript - ReactJS: Rendering the state separately and not as an array
问题描述
I ended up pulling off what I wanted. However, it's giving me an array of the state instead of rendering each one separately. This is probably very simple and I'm more than likely over-complicating it but hey, any help would be nice.
Here's what I currently am dealing with
And here's a better example: https://i.imgur.com/WLDkbOb.gif
And lastly here's probably the best overview: https://imgur.com/a/zintqTA
constructor(props) {
super(props);
this.state = {
data: [],
loading: false,
}
}
ws = new WebSocket(URL)
componentDidMount() {
this.ws.onopen = () => {
console.log('connected')
}
this.ws.onmessage = e => {
const tbox = JSON.parse(e.data);
if(tbox.data && tbox.data.length > 0){
this.setState({
data : this.state.data.concat(tbox.data[0]),
})
}
}
this.ws.onclose = () => {
console.log('disconnected')
this.setState({
ws: new WebSocket(URL),
})
}
}
render() {
let { data } = this.state;
const chatBox = data.map(item => {
return (
<List
key={item.id}
dataSource={this.state.data}
renderItem={item => (
<List.Item >
<List.Item.Meta
avatar={<Avatar size="large" icon="user" />}
title={<div><a href="https://example.com">{item.user}</a> {item.date}</div>}
description={item.message}
/>
</List.Item>
)}
>
</List>
)
})
return (
<div>
<div>
{chatBox}
</div>
I'm trying to loop through the state and render each message separately
解决方案
我认为您不需要循环,this.state.data[]
因为您已经将数据源设置为antd
<List>
组件。antd
List
组件为我们处理对象的集合。这将是渲染您的代码this.state.data
:
const chatBox = <List dataSource={this.state.data}
renderItem={item => (
<List.Item >
<List.Item.Meta
avatar={<Avatar size="large" icon="user" />}
title={<div><a href="https://example.com">{item.user}</a>
{item.date}</div>}
description={item.message}
/>
</List.Item>
)}
>
</List>;
你可以看看这些链接:
推荐阅读
- angular - Angular Material Table 绑定的行数多于行数
- django - 我在 DayArchiveView 中为 django-recurrence 设置 date_field 是什么?
- string - 试图通过命令设置变量。但是一直报错
- python - Tensorflow 2 对象检测 API:CUBLAS 和 CUDNN 的 STATUS_ALLOC_FAILED
- functional-programming - 让 SML 中的绑定和动态范围
- python - BigQuery Python API 最大响应大小和大型查询结果
- python - 从一个数组/数据帧与另一个输出缺失值
- android - 具有自己域的 Android Studio Javamail
- python - 将 pandas 列转换为另一行记录
- excel - 如何使用 VBA 验证动态子列表?