我有问题。我想将响应对象映射到数组。基本上,如果响应也是数组,则使用映射,但是在这种情况下,来自服务器的响应是对象。我该如何映射?
getuser.js
this.state = {
post : '',
post2 : [],
formData : {
username : '',
clientId : ''
}
getPostAPI = (event) => {
event.preventDefault();
const token = localStorage.getItem('token');
const { post } = this.state
const { username } = this.state.formData
axios.post(`http://10.40.22.21:8062/users/get`, { username } ,
{
headers:
{
"Content-Type" : "application/json",
"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"AUTHENTICATION-KEY" : token,
}
})
.then((res)=>{
let response = res;
if(response){
this.setState ({
post : response.data.response
})
console.log(response.data.response)
}
},this)
.catch( (error) => {
alert('Username Tidak di Temukan',error)
}
)
}
GETuser.js中的myForm
{
Object.values(post).map((h,i) => (
<tr key = {i} >
<th scope="row">
<Media className="align-items-center">
<Media>
<span className="badge-dot mr-4">
{h.username}
</span>
</Media>
</Media>
</th>
<th scope="row">
<Media className="align-items-center">
<Media>
<span className="badge-dot mr-4">
{h.firstName}
</span>
</Media>
</Media>
</th>
<th scope="row">
<Media className="align-items-center">
<Media>
<span className="badge-dot mr-4">
{h.password}
</span>
</Media>
</Media>
</th>
<th scope="row">
<Media className="align-items-center">
<Media>
<button className="btn btn-danger" onClick= {() => this.handleRemove(post.clientId)}><i class="fa fa-trash"></i></button>
</Media>
</Media>
</th>
</tr>
))
来自服务器的响应
{
"responseCode":"00",
"message":"Process successful. ",
"localMessage":"Proses Berhasil.",
"response" : {"username":"admin","firstName":"admin","middleName":"is","lastName":"admin","password":"fZE+K9bKT29FAEOaJbfFw==","effectiveDate":"25-01-2019 07:00:00","expiredDate":"25-01-2021 07:00:00","phone":"082234051157","email":"asdsad@gmail.com"}}
我希望无法发布post.map,所以我可以使用acction删除或更新谢谢
答案 0 :(得分:0)
如果要将对象转换为数组,则可以使用以下选项:
1) Object.values(post.response)
将为您提供对象的值作为数组。
2) Object.keys(post.response)
将为您提供对象的键作为数组。
3) Object.entries(post.response)
将为您提供一个数组,其中每个元素都是由键和值组成的数组。
因此,您可以执行以下操作:
Object.keys(response).map( heading =>
<tr>
<th scope="row">
<Media className="align-items-center">
<Media>
<span className="badge-dot mr-4">
{heading}
</span>
</Media>
</Media>
</th>
<td scope="row">
<Media className="align-items-center">
<Media>
<span className="badge-dot mr-4">
{response[heading]}
</span>
</Media>
</Media>
</td>
这样,您可以根据对象属性动态定义列并输出相应的值。
答案 1 :(得分:0)
获得响应后,您可以使用setstate将响应存储在帖子数组中。
this.setState({post2:response})
答案 2 :(得分:0)
哦,随你的情况。您就是这样(ES6):
const result = [ response.data.response ]
this.setState ({
post : result
})
现在,this.state.post将是:
[
{
"username": "admin",
"firstName": "admin",
"middleName": "is",
"lastName": "admin",
"password": "fZE+K9bKasdsaASDJbfFw==",
"effectiveDate": "25-01-2019 07:00:00",
"expiredDate": "25-01-2021 07:00:00",
"phone": "082233051157",
"email": "asdasdasn@gmail.com"
}
]