首页 > 解决方案 > 如何在本机反应中将对象分配给状态?

问题描述

我想将 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
    }
}

标签: reactjsreact-native

解决方案


尝试这个,

 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>
  )
}

希望这可以帮助。


推荐阅读