如何存储json对象本机反应

问题描述 投票:-1回答:2
 {
"code": 200,
"message": "User Login successfully",
"data": {
    "_id": "5da6ebf323410526a25162d2",
    "name": "abcd",
    "email": "[email protected]",
    "preferences": {
        "email": 1,
        "feed": 1,
    },
    "notification_status": "On",
    "updated_at": "2020-12-11 05:36:02",
    "created_at": "2020-10-16 10:07:47",
    "group_ids": [],
    "roles": [
        {
            "_id": "5d96e202c01249370e25b7c9",
            "name": "abcd",
            "guard_name": "web",
            "member_ids": [
                "5da81af673176e067f22545a"

            ]
        }
    ]
}
}

想要将json对象“ data”存储在对象中,并在需要时从“ data”中检索值。怎么办?

json react-native asyncstorage
2个回答
0
投票

您可以使用AsyncStorage存储和检索数据:-

const data = {
"code": 200,
"message": "User Login successfully",
 "data": {
"_id": "5da6ebf323410526a25162d2",
"name": "abcd",
"email": "[email protected]",
"preferences": {
    "email": 1,
    "feed": 1,
},
"notification_status": "On",
"updated_at": "2020-12-11 05:36:02",
"created_at": "2020-10-16 10:07:47",
"group_ids": [],
"roles": [
    {
        "_id": "5d96e202c01249370e25b7c9",
        "name": "abcd",
        "guard_name": "web",
        "member_ids": [
            "5da81af673176e067f22545a"

        ]
    }
]
}
}

// storing data in to local storage
AsyncStorage.setItem("dataKey", JSON.stringify(data))

// retrieving data whenever you need from local storage
AsyncStorage.getItem("dataKey").then(data => {
  if(data){
     let ourData = JSON.parse(data)
     console.log("ourData >>>>> ",ourData)
  }
}).catch(err => console.log("error >>>>> ",err))

0
投票

对于数据存储,我建议您在ReactNative中使用Redux(JavaScript应用程序的可预测状态容器。)。

您可能不希望将所有内容都存储在AsyncStroage上,因为它会将数据持久存储在设备上,因此请选择将数据明智地存储在Redux / AsyncStorage上。

长话短说,下面显示了Redux的概念。 (Img Source from Tutorial Point

enter image description here


简要说明:##(按顺序)

VIEW

  1. 在UI视图上,用户点击一个按钮(说我要得到我的剩余钱包值)

ACTION

  1. 用动作键触发的动作(每个动作都有其自己的特定键,您必须定义)this.props.getWalletValue()
  2. 方法getWalletValue已触发,响应从API返回。

DISPATCH] >>

  1. 来自API的调度响应。在这里,可能是成功/失败状态。
  2. 分派将分派类型传递给Reducer
  3. 归约存储和状态

  1. Reducer然后将值从API响应返回到STORE并保持在STATE
  2. VIEW

  1. 开发人员现在可以通过方法mapStateToProps从Redux获得响应,以获得所需的结果。这些结果来自STORE。

© www.soinside.com 2019 - 2024. All rights reserved.