我有以下组件
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
。
答案 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>
);
}