Luiz E. Luiz E. - 3 months ago 30
Javascript Question

React doesn't call componentWillMount when render returns another component

I have the following components

const Dashboard = React.createClass({
getInitialState(){
return {
user: JSON.parse(localStorage.getItem('user'))
};
},

componentWillMount(){
var self = this;
$.get({
url: 'http://127.0.0.1:8080/v1/rooms',
headers: {
'Auth-Token': self.state.user.backendAccessToken
},
success: function(data){
var rooms = []
for (var i in data) {
rooms.push({id: data[i].uid, content: data[i]})
}
self.setState({rooms: rooms});
console.log(rooms);
}
})
},

render(){
return(
<RoomList rooms={this.state.rooms} />
// <div></div>
);
}
});

export default Dashboard;


and

import React from 'react';
import RoomLink from './RoomLink';

const RoomList = React.createClass({
render: function() {
var roomList = this.props.rooms.map(function(room) {
return (<RoomLink room={room} />)
});
return (
<div>
{ roomList }
</div>
);
}
});
export default RoomList;


when ran, I get
RoomList.js:21 Uncaught TypeError: Cannot read property 'map' of undefined
, and the
console.log
and my success callback is never printed. But when I render an empty div instead of the
RoomList
component, the componentWillMount is called and I can see the response in the logs.

Seems like React is not calling
componentWillMount
.

Answer

ajax call will take time meanwhile child components get rendered with prop rooms as undefined, Need to handle that case.

  render: function() {
    var roomList = (this.props.rooms || []).map(function(room) {
    return (<RoomLink room={room} />)
  });
   return (
    <div>
    { roomList }
    </div>
 );
}

or

render(){
  return(
   <RoomList rooms={this.state.rooms||[]} />
   // <div></div>
  );
}
Comments