[英]How to work with for/in statement and fetch() in React
我正在开发一个调用API
的小型React
项目。
constructor(props){
super(props);
this.state = {users: []};
}
当用户单击按钮时会调用handleSubmit
。 然后该方法调用API
。
handleSubmit = (event) => {
fetch(SERVER_URL + 'api/users')
.then(response => response.json())
.then(responseData => {
this.setState({users: responseData._embedded.users,});
// This is where I'm struggling.
for(const respName in this.state.users.name){
const allNames = respName; // Not working
};
})
.catch(err => console.error(err));
event.preventDefault();
}
JSON
格式的API
响应如下所示:
{
"_embedded": {
"users": [
{
"name": "Tomes",
"lastname": "River",
"birthdate": "13/12/1994",
"adress": "5 rue lolato STR",
"phone": 1234567890,
"email": "user@toto.fr",
"password": "$2a$10$APhzDsJZ/qrz1BoyU3bRXO/OJ59KHQqduaExevABlxNJjud6X92VG",
"role": "ADMIN",
}
]
},
....
}
我想找回里面每一个用户名users
在我handleSubmit
方法。 我想这将是一个for/in
语句,但我无法做到。
您正在寻找的是如何迭代一组 json 对象。 有多种方法可以做到,一种方法是使用forEach()
:
.then(responseData => {
let tempUsers=[];
responseData._embedded.users.forEach((item)=>{
tempUsers.push(item.name);
})
this.setState({users: tempUsers});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.