React.js从数组创建多个表

时间:2017-12-06 11:28:56

标签: javascript html reactjs react-native

我已经找到了解决问题的方法,但没有任何效果可能是因为我缺乏理解。

我正在尝试使用React.js来创建动态长度的表。

我在我的项目中调用API,其中axios库返回一个JSON对象数组,我们不知道返回数组的大小,但对于数组中的每个JSON对象,我需要创建一个表并添加其数据。以下是API调用返回的示例。

[

  {
        "feedbackID": 12,
        "posterID": "John",
        "comment": "shortcomment"
    },
    {
        "feedbackID": 23,
        "posterID": "billy",
        "comment": "long comment"
  }
]

因此,通过此返回,我将创建2个表,一个在另一个下面,如下所示:

| Feedback ID | 12           |
| Poster ID   | John         |
| Comment     | shortcomment |

| Feedback ID | 23           |
| Poster ID   | billy        |
| Comment     | long comment |

到目前为止,这是我的代码:

   export class ViewFeedback extends Component {
  constructor(props) {
    super(props)
    this.state = {
      feedback: []
    }
  }

  componentDidMount() {
    var id = this.props.match.params.id;

    // this returns the JSON array like shown above
    getfeedback(id).then((response) => {


     this.setState({feedback:response})

    })


  }

我根本不知道如何制作表格,我尝试了createElement以及Grid但我做错了它甚至无法编译代码。

2 个答案:

答案 0 :(得分:2)

这应该有效:

renderTable = () => {
    return this.state.feedback.map(value => {
        return (
            <table>
            <tr>   
                <td>Feedback ID</td>
                <td>{value.feedbackID}</td>
            </tr>
             <tr>   
                <td>Poster ID</td>
                <td>{value.posterID}</td>
            </tr>
             <tr>   
                <td>Comment</td>
                <td>{value.comment}</td>
            </tr>
        </table>
        )
    })
}

render () {
    return <div>{this.renderTable()}</div>;
}

渲染方法主要是一个视图,因此鼓励将逻辑移动到单独的方法。

答案 1 :(得分:0)

{this.state.feedback.map(item => {
  return (
    <table>
      <tr>
          <td>Feedback ID</td>
          <td>{item.feedbackID}</td>
      </tr>
      <tr>
          <td>Poster ID</td>
          <td>{item.posterID}</td>
      </tr>
      <tr>
          <td>Comment</td>
          <td>{item.comment}</td>
      </tr>
  </table>
  )
})}

在渲染方法中使用它