React Native foreach循环 [英] React Native foreach loop

查看:545
本文介绍了React Native foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在React Native中开发一个小应用程序,并且正在寻找诸如foreach函数之类的东西.我只是找不到foreach循环.不在StackOverflow上,甚至不在 docs 中.我已经找到了带有地图"的内容,但是我不知道这是否是我想要的.

I'm developing a little app in React Native and I am looking for something like a foreach function. I just can't find a foreach loop. Not on StackOverflow and not even in the docs. 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",

我想将其输出到列表中. 在普通的PHP中,我会为此使用一个foreach循环,但是就像我说的那样,我无法为React Native找到一个foreach循环.

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.

如何循环遍历此对象?我知道我也可以使用简单的for循环,但这绝对不是我的首选...

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...

我将此值与this.setState({users: responseData.users});保存在this.state.users中.状态是在我的构造函数中定义的.我尝试使用this.state.users.map(id => <Text>{id}</Text>)访问此文件,但始终收到相同的错误:null is not an object (evaluating 'this.state.users.map').我这样做正确吗?

I saved this value in this.state.users with 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'). Am I doing this right?

推荐答案

您可以使用 for 或任何其他

You can use map or for-of or any other

示例:

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

根据错误,您可能没有处于users状态的数据,因此您遇到了错误.如果数据正确,则上面的示例将正常工作

as per the error you may not have data within users state, so you are getting error. If data is proper then above example will work properly

这篇关于React Native foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆