如何存储一个JSON对象反应本机

时间:2019-12-11 05:54:53

标签: json react-native asyncstorage

 {
"code": 200,
"message": "User Login successfully",
"data": {
    "_id": "5da6ebf323410526a25162d2",
    "name": "abcd",
    "email": "abcd@example.com",
    "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”中检索值。 怎么办?

2 个答案:

答案 0 :(得分:0)

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

const data = {
"code": 200,
"message": "User Login successfully",
 "data": {
"_id": "5da6ebf323410526a25162d2",
"name": "abcd",
"email": "abcd@example.com",
"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))

答案 1 :(得分: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

降级器和存储和状态

  1. Reducer然后将API响应中的值返回到STORE并保持在STATE

VIEW

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