控制台日志可正确显示对象的键和值,但尝试访问时未定义

时间:2019-09-10 07:32:16

标签: javascript json reactjs object

我从2个不同的API获取订单和工作人员数据。 Orders API获得了workerId,worker API也获得了workerId,因此我需要将其绑定在一起,并显示每张具有订单和工作人员信息的卡。

例如,命令1-汤姆,命令3-杰克...

我设置了一个状态,该状态是一个包含对象的数组,每个对象最终都获得了订单和工作人员信息

例如

{{ if .Values.blue.enabled }}
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: {{ template "blue-green.fullname" . }}-blue
  labels:
    release: {{ .Release.Name }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    app: {{ template "blue-green.name" . }}
spec:
  replicas: {{ .Values.replicaCount }}
  template:
    metadata:
      labels:
        app: {{ template "blue-green.name" . }}
        release: {{ .Release.Name }}
        slot: blue
    spec:
      containers:
        - name: {{ template "blue-green.name" . }}-blue
          image: nginx:stable
          imagePullPolicy: IfNotPresent
          ports:
            - name: http
              containerPort: 80
              protocol: TCP
          # This (and the volumes section below) mount the config map as a volume.
          volumeMounts:
            - mountPath: /usr/share/nginx/html
              name: wwwdata-volume
      volumes:
        - name: wwwdata-volume
          configMap:
            name: {{ template "blue-green.fullname" . }}
{{ end }}

通过console.log,显示键和值看起来没有问题,但是尝试访问辅助数据时,我得到的是不确定的,与订单数据不同。

我的下面的代码:

 {
    "order" : 1,
    "workerName" : "Tom",
      .
      .
      .
  }

1 个答案:

答案 0 :(得分:0)

您不必等待执行,而是直接设置空数据。

尝试这样的事情:

useEffect(async () => {
   let works = []
   const orders = await fetchOrders();
   await Promise.all(orders.map(async work => {
       const worker = await fetchWorkers(work.workerId);
       work.companyName = res.companyName
       work.email = res.email
       work.image = res.image
       work.workerName = res.name
       })
       works.push(work)
     })
     setWorkData(works)
   })
 }, []);

这将等待每次执行并在此之后设置数据。现在,您正在直接在执行提取之前设置数据。