html - 如何在我的 HTML 页面上使用 reactjs 显示此 json 数据
问题描述
我对网页设计非常陌生(实际上没有先验知识),目前正在尝试创建一个网站,该网站使用 Nodejs 从我的 MySQL 数据库中提取数据并使用 Reactjs 将其显示在我的 HTML 页面上。任何帮助将不胜感激
我之前复制了如何在表中使用 ReactJs 显示 json 数据的代码,但是当我使用来自本地主机服务器的 URL 和其中的 JSON 数据时,它只显示错误“TypeError: this.state.data.map is不是函数”。
这是我的 app.js
class App extends React.Component {
constructor(){
super()
this.state = {
data: []
}
}
componentDidMount() {
$.ajax({
url: "http://localhost:4000/stockin",
type: "GET",
dataType: 'json',
ContentType: 'application/json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(jqXHR) {
console.log(jqXHR);
}.bind(this)
})
}
render() {
return (
<table>
<tbody>{this.state.data.map(function(item, key) {
return (
<tr key = {key}>
<td>{item.No}</td>
<td>{item.Stocktype}</td>
<td>{item.Binid}</td>
<td>{item.Stockid}</td>
</tr>
)
})}</tbody>
</table>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
这是我的 json 数据
{"stockin":[{"No":1,"Stocktype":"XM21","Binid":"1234124","Stockid":"135215215","Datestockin":"2019-05-05T16:00:00.000Z","Quantity":52,"Remarks":"Good stock"},
{"No":2,"Stocktype":"XM22","Binid":"2352342","Stockid":"123456721","Datestockin":"2019-05-05T16:00:00.000Z","Quantity":21,"Remarks":"Good stock"},
{"No":3,"Stocktype":"screw","Binid":"2432342","Stockid":"123456721","Datestockin":"2019-05-05T16:00:00.000Z","Quantity":23,"Remarks":"Good stock"},
{"No":4,"Stocktype":"screw","Binid":"1325123","Stockid":"242353223","Datestockin":"2019-04-30T16:00:00.000Z","Quantity":32,"Remarks":"Screws for bins"}]}
我希望最终能够在我的 HTML 网站上以表格形式显示数据。
解决方案
可能是问题最初是数据是空的,所以你必须检查data
类似的长度
{this.state.data.length == 0 && <div>No data found</div>}
{this.state.data.length > 0 &&
<table>
<tbody>{this.state.data.map(function(item, key) {
return (
<tr key = {key}>
<td>{item.No}</td>
<td>{item.Stocktype}</td>
<td>{item.Binid}</td>
<td>{item.Stockid}</td>
</tr>
)
})}</tbody>
</table>
}
推荐阅读
- matlab - 导致旋转弧接触另一条曲线而不相交(Matlab代码)
- c# - 在文件上传中添加日期过滤器,同时单击 asp.net 网络表单中的文件上传按钮
- reactjs - React Native:createBottomTabNavigator screenOptions 不起作用
- harmon.ie - 通过harmon.ie 保存电子邮件 - 如果查看邮件的人没有前景怎么办?
- r - R Shiny - 将 JS 文件添加到 HTML 模板
- powershell - 我尝试使用 power shell 下载图像文件,但出现以下错误
- python - 在 Docker Hub 上找不到合适的图像,而它在 Bitbucket 上似乎运行正常
- opengl - OpenGL绘制多个对象
- php - 使用 WriteHtml -PHP 支持中文、日文和英文的 TCPDF 字体
- javascript - 如何从嵌套数组中删除对象?