Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to display a json dataset on my localhost browser after getting it with a GET http request from a server.

Code:

imports ...
      
  class See extends Component {
      state = { 
         Sessions :[] , 
       }
       

       async componentDidMount(){
           
        const {data: Sessions}= await axios.get("http://localhost:8765/...");
        
        this.setState({Sessions});
    
       }
      render() { 
        
          return ( 
            <React.Fragment>
              <Table striped bordered hover>
                 <thead>
                   <tr> 
                     <th>PointID</th>
                     <th>PointSessions</th>
                     <th>EnergyDelivered</th>
                   </tr>
                 </thead>
                <tbody>
                {this.state.Sessions.SessionsSummaryList.map(Session => (
                   <tr key="Session.PointID">
                   <th>Session.PointID</th>

                   </tr>  
                   ))}
             </tbody>
          </Table>
        </React.Fragment>                            
          );  }
  }
   
  export default See;

This dataset consists of some data fields as well as a list of json object(each one containing 3 fields as shown in Table Headers).

Using the React extention in chrome dev tools i can see that the dataset is loaded in state and is looking like it is supposed to,however i am getting this error:

TypeError: Cannot read property 'map' of undefined

What i also saw with a simple print is that the render method is called 2 times during the run of this code.Is it that the Sessions value is not initialized in the first run?

If yes how can i solve this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
309 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can check if the array exits first, destructure and then do the following:

const { SessionsSummaryList } = this.state.Sessions || {}; 
 
{ SessionsSummaryList && SessionsSummaryList.map(
  ....
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...