我是React世界的新手,我正在努力让我的JSON数据显示在表格中。
class GetUnassignedUsers extends React.Component {
constructor () {
super();
this.state = {
data:[]
};
}
componentDidMount () {
fetch("http://localhost/dashboard/?action=unassignedUsers.getUnassingedUsers", {
credentials: 'same-origin'
})
.then(response => response.json())
.then(json => this.setState({data: json}));
}
render () {
console.log("teams", this.state.data.teams);
console.log("unassignedUsers", this.state.data.unassignedUsers);
var teams = this.state.data.teams;
var unassignedUsers = this.state.data.unassignedUsers;
return (
<tr>
<td>
{unassignedUsers.ID}
</td>
<td>
23/08/2015
</td>
<td>
Tradeprint
</td>
<td>
name@tradeprint.co.uk
</td>
<td>
John Bloggs
</td>
<td>
Aberfeldy
</td>
<td>
AD9 8QR
</td>
<td>
Unassigned
</td>
</tr>
);
}
};
export default GetUnassignedClients;
我正在访问JSON并在2个控制台日志(console.log("teams", this.state.data.teams);
和console.log("unassignedUsers", this.state.data.unassignedUsers);
)中的render方法中返回它。
我的问题在于我通过为团队和未分配的用户声明2个变量来整理点符号。然后在我的回访中,我想为第一个<td>
中的unassignedUser ID为每个JSON记录生成一行。
答案 0 :(得分:1)
要动态创建表行,你需要迭代json并创建ui项,如下所示:
return (
<table>
<tbody>
{unassignedUsers.map((item,index)=>{
return <tr key={index}>
<td>
{item.ID}
</td>
<td>
23/08/2015
</td>
<td>
Tradeprint
</td>
<td>
name@tradeprint.co.uk
</td>
<td>
John Bloggs
</td>
<td>
Aberfeldy
</td>
<td>
AD9 8QR
</td>
<td>
Unassigned
</td>
</tr>
})
</tbody>
</table>
);
答案 1 :(得分:1)
var unassignedUsers = this.state.data.unassignedUsers; // Probably it returns array of users
所以你要做的就是:
var rows = unassignedUsers.map(function(user) {
return (<tr>
<td>{user.ID}</td>
<td>{user.somethingElse}</td>
</tr>)
});
return (
<table>
<tbody>
{rows}
</tbody>
</table>
)
答案 2 :(得分:0)
在您的情况下,我会使用现有的组件,例如Reactable Table作为一个很好的启动。
import React from "react";
import ReactDOM from "react-dom";;
import Reactable from "reactable";
var Table = Reactable.Table;
ReactDOM.render(
<Table className="table" data={[
{ Name: 'Griffin Smith', Age: 18 , Position: 'Schoolar'},
{ Age: 23, Name: 'Lee Salminen', Position: 'Student'},
{ Age: 28, Name: 'Mike Kofs', Position: 'Developer' },
]} />,
document.getElementById('app')
);