【问题标题】:unable to access dynamic object property and store to state in react无法访问动态对象属性并存储到反应状态
【发布时间】:2021-08-27 03:40:42
【问题描述】:

我正在尝试从 nasa 开放 api 之一中获取这些数组 -> https://api.nasa.gov/neo/rest/v1/feed?start_date=START_DATE&end_date=END_DATE&api_key=API_KEY

我在参数中有一个动态日期,因此返回的对象与日期匹配,有什么方法可以使用我的日期(即使它是一个字符串)并将其转换为“键”值,以便我可以动态获取我需要什么物品?

like => "2021-08-26" 将引用 { 2021-08-26: [{},{},{}...] }

到目前为止,我已将我的代码包含在我尝试过的内容中,目前我正在尝试使用 forEach 选择 {near_earth_objects} 内的所有键,但我仍然收到错误 data.near_earth_objects.forEach is not a function

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

    //grab the current time  (year-month-day) and store it in the state
    componentWillMount(){
        var today = new Date();
        var start = today.getFullYear()+'-'+0+(today.getMonth()+1)+'-'+today.getDate();  
        var end = today.getFullYear()+'-'+0+(today.getMonth()+1)+'-'+(today.getDate()+1); 

        this.setState({time: [start,end]})
    }


    componentDidMount(){
        
        fetch(`https://api.nasa.gov/neo/rest/v1/feed?start_date=${this.state.time[0]}&end_date=${this.state.time[1]}&api_key=ipAxYzaENbqRKb7GgzFPcH6QUBsHXY3QKB7uXOf5`
        )
      .then(response => response.json())
      .then((data) => {
            let asteroids = []
            data.near_earth_objects.forEach((arr)=>{
            asteroids.push(arr)
        })
        this.setState({asteroids:asteroids})
      });
    }
   

这是我尝试访问的记录数据的示例

【问题讨论】:

  • 检查您的响应日志,near_earth_objects 不是数组,因此无法迭代。

标签: reactjs object react-hooks key


【解决方案1】:

请务必注意,数据以对象的形式返回,其中值是数组。由于返回数据是一个对象,因此您无法对其进行迭代。

但是,要获取数据,您可以通过Object.values(object) (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) 获取值数组。这将返回类似于 [ [...], [...] ]

的内容

之后,您可以遍历此信息。

最后你的代码应该是这样的:

Object.values(data.near_earth_objects).forEach((arr)=>{
    asteroids.push(...arr)
})

【讨论】:

  • 啊,我明白了,是的,我能够使用这个例子来让它工作:) 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
  • 2021-11-09
  • 2011-08-10
  • 2019-03-20
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
相关资源
最近更新 更多