繁体   English   中英

如何在 React 中使用 for/in 语句和 fetch()

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM