繁体   English   中英

如何在reactjs中访问JSON数组的元素?

[英]How to access elements of an array of JSON in reactjs?

我正在尝试将JSON对象数组提取到我的react页面上。 现在,我得到的数组是:

[{"_id":"5c4309fb643589310818165e","TableTime":"10:30- 11:00","TableType":"Pool Table 1","TableStatus":"Booked"}, {"_id":"5c430a3f2f788e322d2430d0","TableTime":"10:30- 11:00","TableType":"Pool Table 1","TableStatus":"Booked"}]

我首先在componentDidMount()方法的状态变量result中设置它。 render方法中,当我这样做时:

    const { result } = this.state;
    var slot = result;    
    console.log(slot);

我得到上面的数组。 但是当我这样做时:

    const { result } = this.state;
    var slot = result;    
    console.log(slot[0].TableTime);

我收到错误TypeError: Cannot read property 'TableTime' of undefined

我搜索了它并尝试了此链接,并使用JSON.parse()在jquery中的数组中访问json的元素

但是随后它给了我错误: SyntaxError: Unexpected token u in JSON at position 0

相关代码如下:

 class Timeslots extends Component {
  constructor(props, context) {
  super(props, context);
  this.state = {
    result: [] 
 }

  componentDidMount() {
    this.getList();
  }

  getList = () => {

    fetch("/purchase")
    .then(res => res.json())
    .then(result => this.setState({ result }))
  }


  render() { 
    const { result } = this.state;
    var slot = result;    
    console.log(slot);
   );
  }
 }

 export default Timeslots; 

我只是想要一种方法,以便可以访问slot[0].TableTime并使用它?

首先,组件渲染。 然后,您从fetch获得结果。 因此,您应该在渲染中进行null检查。 类似于返回结果!== null? 执行console.log(结果):空

另外,插槽变量不是必需的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM