提取后无法访问状态数组

时间:2019-07-14 02:52:02

标签: reactjs

我正在尝试访问workerId(位于json文件中,以将其用于应用程序中的第二次提取,以便显示工作人员信息)。提取工作并显示数据,但是当我console.log(this.state.ordersData.workerId)时,出现错误,它是未定义的。如何获取workerId并将其存储在变量中?

我的json的一部分在下面:

{
    "orders": [
        {
            "deadline": 1563046159,
            "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            "id": "83f007d6",
            "name": "Work order 83f007d6",
            "workerId": 1
        },
        {
            "deadline": 1562752687,
            "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            "id": "cb23c526",
            "name": "Work order cb23c526",
            "workerId": 1
        },
]
}

下面的App.js的一部分:

  import React, { Component } from 'react';
    import Order from './components/Order';
    import Form from './components/Form'
    import './App.css';

class App extends Component {

constructor(props) {
  super(props);
  this.state={
    ordersData: []
  }
} 

  componentDidMount() {

    fetch("https://www.hatchways.io/api/assessment/work_orders")
      .then(response => response.json())
      .then(data => {
        this.setState({
          ordersData: data.orders
          });
          console.log(this.state.ordersData.workerId)
        })
      .catch(err => {
        console.log(err)
      }); 
  }

在控制台中显示未定义

编辑1

fetch(`https://www.hatchways.io/api/assessment/workers/${workerId}`)
        .then(response => response.json())
        .then(data => {
          this.setState({
            workersData: data,
          });

        })
        .catch(err => {
          console.log(err)
        });

编辑2

import React, { Component } from 'react'
import Worker from './Worker'

import Moment from 'react-moment';
import '../App.css'


class Order extends Component {

state={
        workersData :{worker:[]} ,

    }


componentDidMount() {
    let workerId = this.props.workerId;
    fetch(`https://www.hatchways.io/api/assessment/workers/${workerId}`)
        .then(response => response.json())
        .then(data => {
          this.setState({
            workersData: data,
          });

        })
        .catch(err => {
          console.log(err)
        });
    }



    render(){
        let workerId = this.props.workerId;
        console.log(workerId);

        return(

            <div className ='order-card'>
                <div >
                    <p>{this.props.orderName}</p>
                    <p>{this.props.description}</p>
                </div>
                <Worker name = {this.state.workersData.worker.name}
                        email = {this.state.workersData.worker.email}
                        companyName = {this.state.workersData.worker.companyName}
                        image = {this.state.workersData.worker.image}/>
                <div className="order-card-time"><span className = 'bold'>Deadline :</span><Moment format="YYYY/MM/DD HH:mm">{this.props.deadline}</Moment></div> 
            </div>
        )
    }

}
export default Order;

1 个答案:

答案 0 :(得分:0)

setStateasync,因此console.log仅由于尚未设置状态而显示未定义,您可以在callback中使用setState

this.setState({
   ordersData: data.orders
},() => console.log(this.state.ordersData[0].workerId));

更新

您可以使您成为componentDidUpdate,因为在孩子componentDidMount执行您的parent'ssetState由于async的性质而未被执行。

componentDidUpdate(prevProps, prevState) {
   if(prevProps.workerId !== this.props.workerId){
    let workerId = this.props.workerId;
    fetch(`https://www.hatchways.io/api/assessment/workers/${workerId}`)
        .then(response => response.json())
        .then(data => {
          this.setState({
            workersData: data,
          });

        })
        .catch(err => {
          console.log(err)
        });
    }
}