当render返回另一个组件

时间:2016-08-21 15:45:58

标签: javascript reactjs

我有以下组件

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;

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;

运行时,我得到RoomList.js:21 Uncaught TypeError: Cannot read property 'map' of undefined,而console.log和我的成功回调从未打印过。但是当我渲染一个空div而不是RoomList组件时,会调用componentWillMount,我可以在日志中看到响应。
似乎React没有调用componentWillMount

1 个答案:

答案 0 :(得分:2)

ajax调用将花费时间,同时子组件将使用未定义的道具室进行渲染,需要处理该案例。

outputTextview.string? = respArray.joinWithSeparator(" ")

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