简体   繁体   English

无法在反应中显示存储在状态对象中的数据

[英]Not able to display the data stored in a state object in react

I am new to react and am trying to display the content of a json file in a component.The json file has three data fields of a single object and it is fetched using axios into my component.我是新来的,并试图在组件中显示 json 文件的内容。json 文件具有单个对象的三个数据字段,并使用 axios 将其提取到我的组件中。 The data is successfully retrieved and the state is also set(found from console.log), but when i try to display the data in the render method, it is not recognised and nothing is displayed(ie {this.state.lockerData.data['location']} doesn't work).数据被成功检索并且状态也被设置(从console.log找到),但是当我尝试在render方法中显示数据时,它无法识别并且没有显示任何内容(即{this.state.lockerData.data['location']}不起作用)。 Any help is much welcome.非常欢迎任何帮助。 Thanks in advance!提前致谢!

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import axios from 'axios';



class LockerCard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {lockerData:''}

  }
  componentDidMount() {
    this.getLockerData();
  }

  getLockerData() {
    axios.get('lockerDetails.json').then(response => {
      this.setState({lockerData: response})
      console.log(response.data);

      console.log(this.state.lockerData.data['location']);
    })

  };


  render() {
    return (
      <div>
      <div className="grid-item">
    <span id="location" >{this.state.lockerData.data['location']}</span>
          <br /><br />
          <b>&pound;<span id="cost">{}</span></b>
          <br/><br/>
          <span id="lockeruse">{}</span>
          <br/>
          <input type="button" id="openButton"  value="Open" />&nbsp;&nbsp;
          <input type="button" id="releaseButton" value="Release" />    
      </div>
      </div>
    );
  }
}
  ReactDOM.render(<LockerCard />,document.getElementById('root'));

Access like this {this.state.lockerData.location}像这样访问{this.state.lockerData.location}

return (
      <div>
      <div className="grid-item">
        <span id="location" >{this.state.lockerData.location}</span>
          <br /><br />
          <b>&pound;<span id="cost">{}</span></b>
          <br/><br/>
          <span id="lockeruse">{}</span>
          <br/>
          <input type="button" id="openButton"  value="Open" />&nbsp;&nbsp;
          <input type="button" id="releaseButton" value="Release" />    
      </div>
      </div>
    );

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

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