简体   繁体   English

React Native foreach循环

[英]React Native foreach loop

I'm developing a little app in React Native and I am looking for something like a foreach function. 我正在使用React Native开发一个小应用程序,我正在寻找类似foreach函数的东西。 I just can't find a foreach loop. 我只是找不到foreach循环。 Not on StackOverflow and not even in the docs . 不在StackOverflow上,甚至在文档中也没有。 I've found something with 'map', but I don't know if this is what I'm looking for. 我找到了'地图'的东西,但我不知道这是不是我正在寻找的东西。

With a request to my Server I get multiple objects of users. 通过对我的服务器的请求,我得到了多个用户对象。 When I log the result, it looks like this: 当我记录结果时,它看起来像这样:

Object {
    "id": "1",
    "role": "user",
    "username": "user1",
  },
Object {
    "id": "2",
    "role": "admin",
    "username": "user2",

I'd like to output this to a list. 我想将其输出到列表中。 In plain PHP I would use a foreach loop for this, but like I said, I can't find a foreach loop for React Native. 在普通的PHP中,我会使用foreach循环,但就像我说的,我找不到React Native的foreach循环。

How is it possible to loop trought this objects? 怎么可能循环这些物体呢? I know that I could also use a simple for loop, but this would definitly not be my first choice... 我知道我也可以使用一个简单的for循环,但这肯定不是我的第一选择......

EDIT: I saved this value in this.state.users with this.setState({users: responseData.users}); 编辑:我使用this.setState({users: responseData.users});将此值保存在this.state.users this.setState({users: responseData.users}); . State is defined in my constructor. 状态在我的构造函数中定义。 I try to access this with this.state.users.map(id => <Text>{id}</Text>) but I always get the same error: null is not an object (evaluating 'this.state.users.map') . 我尝试使用this.state.users.map(id => <Text>{id}</Text>)但我总是得到相同的错误: null is not an object (evaluating 'this.state.users.map') Am I doing this right? 我这样做了吗?

You can use map or for-of or any other 您可以使用mapfor-of或任何其他

Example: 例:

// for of
for (let userObject of this.state.users) {
    console.log(userObject.username);
}
// map
this.state.users.map((userData) => {
    console.log(userData.username);
});

as per the error you may not have data within users state, so you are getting error. 根据错误,您可能没有users状态中的数据,因此您收到错误。 If data is proper then above example will work properly 如果数据正确,那么上面的示例将正常工作

In react, preferred way is map method of Array. 在反应中,首选方式是A​​rray的map方法。 Example using ES6 arrow function: 使用ES6箭头功能的示例:

render() {    
    return (
        <View>    
           {dataList.map(r => <Button>{r}</Button>)}    
        </View>
    )
}

You can also use lodash (npm install lodash) and run the following: 您还可以使用lodash(npm install lodash)并运行以下命令:

import _ from 'lodash';

...

_.each(dataList, function(userObject, key) { console.log(userObject, key); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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