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

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


我将使用 id 将它传递到一个 fetch url。


我尝试使用 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)


眼眸繁星
浏览 196回答 1
1回答

慕勒3428872

您需要在回调中获取 idsetState以确保它已被设置: 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)) }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript