javascript - 在 React 中使用对象数组作为 props

标签 javascript arrays rest reactjs

我正在构建一个使用 REST API 的小型应用程序。我在显示对象数组内的信息时遇到问题,请参阅下面的代码:

actions.js

import axios from 'axios'

function fetchService () {
  return axios.get('http://localhost:5000/ldbws-rest-proxy/v0.1/departure-board/IPS')
    .then(function (response) {
      return {
        service: response.data.trainServices[0]
      }
    })
    .catch(function (response) {
      console.log(response)
    })
}

export default fetchService

train_service.js

import fetchService from '../actions'

import DepartureTime from './departure_time'
import OriginStation from './origin_station'

var TrainService = React.createClass ({
  getInitialState () {
    return {
      service: []
    }
  },
  componentDidMount () {
    fetchService()
      .then(function (dataObj) {
        this.setState({
          service: dataObj.service
        })
      }.bind(this))
  },
  render () {
    return (
      <section>
        <DepartureTime time={this.state.service.std} />
        <OriginStation name={this.state.service.origin[0].crs} />
      </section>
    )
  }
})

export default TrainService

JSON 示例 (response.data.trainServices[0])

{
  "destination": [
    {
      "crs": "CBG",
      "locationName": "Cambridge"
    }
  ],
  "etd": "On time",
  "operator": "Greater Anglia",
  "operatorCode": "LE",
  "origin": [
    {
      "crs": "IPS",
      "locationName": "Ipswich"
    }
  ],
  "serviceID": "ILZn7gyLj+eoZZfyaFlP0w==",
  "std": "12:20"
}

问题是 <OriginStation name={this.state.service.origin[0].crs} />抛出错误:

TypeError: undefined is not an object (evaluating 'this.state.service.origin')

我不知道为什么这不起作用,如果我这样做的话console.log(dataObj.service.origin[0].crs)在 componentDidMount 内部它输出良好。我认为这与原始数组有关......

感谢任何帮助。

编辑:

Chrome 检查器中的状态屏幕截图:

Screenshot

最佳答案

这是因为您的 TrainService 渲染方法调用早于 fetchService promise 解析。 修复错误的最简单方法是等待 fetchService 更新 service 状态:

var TrainService = React.createClass ({
  getInitialState () {
    return {
      service: null
    }
  },
  componentDidMount () {
    fetchService()
      .then(function (dataObj) {
        this.setState({
          service: dataObj.service
        })
      }.bind(this))
  },
  render () {
    if (this.state.service === null)
      return null;
    return (
      <section>
        <DepartureTime time={this.state.service.std} />
        <OriginStation name={this.state.service.origin[0].crs} />
      </section>
    )
  }
})

关于javascript - 在 React 中使用对象数组作为 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41979368/

相关文章:

c# - 使用 .NET 4.5 HttpClient 中的域凭据调用 REST 服务

JavaScript 函数参数语句

java - 为什么 `Integer[100] arr;`无效,而 `Ineger[] arr;`有效?

javascript - Bootstrap collapse - 同时打开多个 Accordion

JavaScript:动态创建数组

javascript - 在javascript中对数组对象进行排序

java - 获取错误 : Error reading entity from input stream

java - 为 REST API 返回部分成功响应的好方法是什么?

javascript - 右键单击停止传播

javascript - switch div 函数中 JavaScript 的时间延迟