Реагировать нативно получить определенное значение элемента из массива состояний - PullRequest
0 голосов
/ 27 октября 2019

Я новичок в React-Native. Я создаю пример приложения, но у меня возникла небольшая проблема с this.state.array. Я хочу, чтобы конкретное значение элемента из массива было моим массивом

this.state.userDetail: [
  Object {
    "creation_Date": "2019-10-22T06:34:52.000Z",
    "mobile": 9985849955,
    "name": "siva",
    "password": "123456",
    "picture_url": "5.jpg",
    "role": "",
    "user_id": 1,
  },
]

````````````````````````````````````````
In the above array i want user_id value ,
i tried different methods like

```````````````````````````

this.setState({ user_id: this.state.user_Details.user_id })

const item_id = this.state.user_Details.map((item) => { item.user_id });

var item_id = this.state.user_Details.filter(userDetails => {  return userDetails[7]; })
 ``````````````````````````````````````````



but nothing will work i want only user_id value to update the users table , So please any help ..

Ответы [ 2 ]

0 голосов
/ 28 октября 2019

Если вы хотите извлечь user_id ОСОБЕННО из этого примера:

[
  {
    "creation_Date": "2019-10-22T06:34:52.000Z",
    "mobile": 9985849955,
    "name": "siva",
    "password": "123456",
    "picture_url": "5.jpg",
    "role": "",
    "user_id": 1,
  },
]

и предполагая, что эти данные находятся в вашем this.state.userDetail свойстве. Единственное, что вам нужно:

this.state.userDetail[0].user_id

Почему это может не сработать для вас:

this.state.userDetail: [
  Object { /// What's Object?

И если вы пытаетесь проанализировать более 1 записи в массиве, в отличие от вашегоНапример, сначала вам нужно выбрать определенную запись с помощью цикла for или функции .map ().

0 голосов
/ 27 октября 2019

Я думаю, вы хотите получить один индексный идентификатор пользователя, поэтому я даю следующий код:

// define it in the constructor, and it may have more than one items
this.state.userDetail: [
   {
    "creation_Date": "2019-10-22T06:34:52.000Z",
    "mobile": 9985849955,
    "name": "siva",
    "password": "123456",
    "picture_url": "5.jpg",
    "role": "",
    "user_id": 1,
  },
]

// do not directly assign use this.state.x
let copyUserDetails = {...this.this.state.user_Details}
let userIdsArray = copyUserDetail.map((item) => { return item.user_id });
let itemId = userIdsArray[0]
console.log("the first user Id is",itemId)
// if you only want to the user_id, you can directly copyUserDetails[0].user_id
let userId = copyUserDetails[0].user_id
console.log("the first user Id is  ==> ",userId)
this.setState({ user_id: itemID })


// the filter is accordng some condtion to return a new arry
let  itemFilterArray = copyUserDetails.filter((element,i) => { 
  // filter the item which match some condition, for example the uerId not equal 
  //0 
  if(element.user_id !== 0){
       return element
    }
})

в соответствии с вашими требованиями, я даю следующий код:

//if you do not have many userInfo
constructor(props){
   super(props)
   this.state= {
   user_Details: {
    "creation_Date": "2019-10-22T06:34:52.000Z",
    "mobile": 9985849955,
    "name": "siva",
    "password": "123456",
    "picture_url": "5.jpg",
    "role": "",
    "user_id": 1,
    }
  }

  // somewhere you want the userId
  getUserId = () => {
      return this.state.user_Details.user_id
   }





}
//if you have many userinfo
constructor(props){
   super(props)
   this.state= {
   user_Details: [{
    "creation_Date": "2019-10-22T06:34:52.000Z",
    "mobile": 9985849955,
    "name": "siva",
    "password": "123456",
    "picture_url": "5.jpg",
    "role": "",
    "user_id": 1,
    }]
  }

  // somewhere you want the some index userId
  getUserId = (index) => {
     // do not directly assign use this.state.x
     let copyUserDetails = {...this.this.state.user_Details}
     return copyUserDetails[index].user_id
   }
   //somwhere you want all the userId
  getUserId = () => {
      // do not directly assign use this.state.x
     let copyUserDetails = {...this.this.state.user_Details}
     let userIdArray = copyUserDetail.map((item) => { return item.user_id });
     return userIdArray
   }
}




и я предлагаю вам прочитать API о JSON и массив

...