首页 > 解决方案 > 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

标签: javascriptreactjsantd

解决方案


我认为您不需要循环,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>;

你可以看看这些链接:


推荐阅读