【发布时间】:2019-09-30 02:28:41
【问题描述】:
我对网页设计非常陌生(实际上没有任何先验知识),目前正在尝试创建一个网站,该网站使用 Nodejs 从我的 MySQL 数据库中提取数据并使用 Reactjs 将其显示在我的 HTML 页面上。任何帮助将不胜感激
我之前从 how to display json data with ReactJs in the table 复制了代码,但是当我使用本地服务器中的 URL 和其中的 JSON 数据时,它只显示错误“TypeError: this.state.data.map is not a function” .
这是我的 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 网站上以表格形式显示数据。
【问题讨论】:
-
您的响应数据不是直接的数组。你可能不得不做
this.setState({ data: data.stockin }) -
没错,也不推荐使用jquery和react,你可以尝试用axios做同样的事情
-
@MaazSyedAdeeb 非常感谢你,我按照你说的做了,现在它完美地工作了!谢谢