簡體   English   中英

React Native foreach循環

[英]React Native foreach loop

我正在使用React Native開發一個小應用程序,我正在尋找類似foreach函數的東西。 我只是找不到foreach循環。 不在StackOverflow上,甚至在文檔中也沒有。 我找到了'地圖'的東西,但我不知道這是不是我正在尋找的東西。

通過對我的服務器的請求,我得到了多個用戶對象。 當我記錄結果時,它看起來像這樣:

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

我想將其輸出到列表中。 在普通的PHP中,我會使用foreach循環,但就像我說的,我找不到React Native的foreach循環。

怎么可能循環這些物體呢? 我知道我也可以使用一個簡單的for循環,但這肯定不是我的第一選擇......

編輯:我使用this.setState({users: responseData.users});將此值保存在this.state.users this.setState({users: responseData.users}); 狀態在我的構造函數中定義。 我嘗試使用this.state.users.map(id => <Text>{id}</Text>)但我總是得到相同的錯誤: null is not an object (evaluating 'this.state.users.map') 我這樣做了嗎?

您可以使用mapfor-of或任何其他

例:

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

根據錯誤,您可能沒有users狀態中的數據,因此您收到錯誤。 如果數據正確,那么上面的示例將正常工作

在反應中,首選方式是A​​rray的map方法。 使用ES6箭頭功能的示例:

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

您還可以使用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