reactjs - 如何在本机反应中将对象分配给状态?
问题描述
我想将 JSON 对象分配给本机反应的状态。
this.state = {
card: null
}
_getCardDetails() {
getItem('userData').then(data => {
this.setState({
card: data.user.creditCard
})
})
}
render() {
const { card } = this.state
return (
<Text>{card}</Text>
)
}
我从axios
对我的后端的调用中获取 JSON 对象。但是我不能将该对象分配给 React Native 中的状态。
来自的回应_getItem()
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjo4MzY5NDc5ODk5fSwiaWF0IjoxNTgwMzU1NjkyfQ._tYykbMtegpl58Poat0w2PsMUpnGFypqFd_7P2s6wQ8",
"next": true,
"user": {
"isProfileComplete": false,
"createdAt": "2020-01-28T11:42:53.413Z",
"_id": "5e302aa091741b14c0ef18bc",
"phone": 8369479899,
"creditCard": {
"createdAt": "2020-01-28T11:42:53.440Z",
"creditCardExpiry": "2021-01-28T11:42:53.440Z",
"_id": "5e302aa091741b14c0ef18bb",
"creditCardNo": 512723298971919,
"creditCardCVV": 381,
"__v": 0
},
"__v": 0
}
}
解决方案
尝试这个,
this.state = {
cardDetails: null,
}
_getCardDetails() {
getItem('userData').then(data => {
this.setState({
cardDetails: data.user.creditCard
})
})
}
render() {
const { cardDetails } = this.state
return (
<Text>{cardDetails.creditCardNo}</Text>
)
}
希望这可以帮助。
推荐阅读
- spring - 我在压力测试下遇到了 websocket (PlayFramework) 的问题
- javascript - 使用现有值更新字段
- javascript - 将外部脚本添加到 React 并创建新实例
- python - 从另一个 Python 进程调用 OS 的 Python 可执行文件
- c# - WPF - 使用 C# 从 WPF 中的 Mysql 数据库中检索(选择或下载)图像
- jquery - 无法使用引导程序 4 和角度 6 根据条件显示模态
- python - 变量范围(带线程)
- java - 试图从firebase获取密钥,而不是获得一条奇怪的路径
- lua - 如何反编译这个 Lua 字节码?
- vis.js - 消除由 8 个底层树组成的 vis 网络中节点的重叠