如何使用reactjs状态从数组中的项目访问数据?

时间:2019-10-31 19:40:57

标签: javascript reactjs react-native

我正在尝试从我从Django-rest API获取的数组中的主对象获取数据(id)。

我将使用ID将其传递到获取网址中。

我尝试使用item.id,但没有获得id值。

这是“任务”数组的格式。

[
    {
        "title": "Task 4",
        "description": "Task 4",
        "video": "ad12312312",
        "done": false,
        "steps": [
            {
                "title": "Task 4 Task 1",
                "description": "Task 4 Task 1",
                "done": false,
                "task_id": 4,
                "id": 10
            },
            {
                "title": "Task 4 Task 2",
                "description": "Task 4 Task 2",
                "done": false,
                "task_id": 4,
                "id": 11
            },
            {
                "title": "Task 4 Task 3",
                "description": "Task 4 Task 3",
                "done": false,
                "task_id": 4,
                "id": 12
            }
        ],
        "id": 4
    }
]
class Screen extends Component {

  constructor() {
    super();
    this.state = {
      task: [],
    };
  }

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
    fetch('https://url.com/daily-ecommerce/', {
      method: 'GET',
      headers: {
        'Authorization': `Token xxxxx`
      }
    })
    .then( res => res.json())
    .then( jsonRes => this.setState({ task: jsonRes }) )
    .catch( error => console.log(error))
    .then(console.log(this.state.task.id))
    fetch(`https://url.com/step/?task_id=${this.state.task.id}`, {
      method: 'GET',
      headers: {
        'Authorization': `Token xxxxx`
      }
    })

我需要访问任务的ID。 (在本例中为“ id”:4)

1 个答案:

答案 0 :(得分:1)

您需要在setState的回调中获取ID,以确保已设置ID:

 componentDidMount() {
   AppState.addEventListener('change', this._handleAppStateChange);
   fetch('https://url.com/daily-ecommerce/', {
       method: 'GET',
       headers: {
         'Authorization': `Token xxxxx`
       }
     })
     .then(res => res.json())
     .then(jsonRes => this.setState({
       task: jsonRes
     }, () => {
       fetch(`https://url.com/step/?task_id=${this.state.task[0].id}`, {
         method: 'GET',
         headers: {
           'Authorization': `Token xxxxx`
         }
       })
     }))
     .catch(error => console.log(error))
 }

另一种方法是直接从json响应中传递ID:

  componentDidMount() {
   AppState.addEventListener('change', this._handleAppStateChange);
   fetch('https://url.com/daily-ecommerce/', {
       method: 'GET',
       headers: {
         'Authorization': `Token xxxxx`
       }
     })
     .then(res => res.json())
     .then(jsonRes => {
       this.setState({
         task: jsonRes
       })
       fetch(`https://url.com/step/?task_id=${jsonRes[0].id}`, {
         method: 'GET',
         headers: {
           'Authorization': `Token xxxxx`
         }
       })
     })
     .catch(error => console.log(error))
 }