我试图从spring引导层获取数据并使用表格形式的react js在前端渲染它。但是我看到下面提到的错误。
我希望以表格形式看到json数据但是我在map function.TypeError:this.state.currencies.map不是函数时出错。下面提到的是UI代码。
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
import {Table} from 'react-bootstrap';
class AppCrypto extends Component{
constructor(props) {
super(props);
this.state = {currencies: [
{id:null,currencyname:null,currencyticker:null}
]
};
}
componentDidMount() {
fetch('/secretdata/allcurrency/',{
method:'GET',
headers:{
'Content-Type':'application/json'
}
})
.then( function(response){
return response.json();
})
.then(function(myJson){
return JSON.stringify(myJson);
})
.then (crypto => {
console.log(crypto);
this.setState({currencies:crypto});
});
}
render(){
return(
<div className="container-fluid">
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>ID</th>
<th>CURRENCY_NAME</th>
<th>CURRENCY_TICKER</th>
</tr>
</thead>
<tbody>
{this.state.currencies.map(function(item, key){
return(
<tr key={key}>
<td>{item.id}</td>
<td>{item.currencyname}</td>
<td>{item.currencyticker}</td>
</tr>
)
})}
</tbody>
</Table>
</div>
);
}
}
export default AppCrypto;
你不应该使用JSON.stringify。 stringify将json转换为字符串。您正在将状态字符串存储在状态而不是数组中。
因此,如果您希望将数据作为数组,请使用JSON.parse(str)或检查响应是否已经是有效的json。