【发布时间】:2017-02-24 10:23:52
【问题描述】:
代码如下:
class Twitch extends React.Component {
constructor(props){
super(props);
this.state={
channelList:null,
streamError:false,
channelError:false,
}
self=this;
this.getChannels = this.getChannels.bind(this);
}
componentWillMount() {
this.getChannels();
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.channelList !== nextState.channelList) {
return true;
}
return false;
}
getChannels(){
let channels=["ESL_SC2", "OgamingSC2",
"cretetion", "freecodecamp",
"storbeck", "habathcx",
"RobotCaleb", "noobs2ninjas",
"brunofin", "comster404"
];
let resultSet=[];
channels.map(function(channel){
axios.get('https://wind-bow.gomix.me/twitch-api/streams/'+channel)
.then(function (response) {
let resObj={};
resObj=response.data;
axios.get('https://wind-bow.gomix.me/twitch-api/channels/'+channel)
.then(function (response) {
resObj.channel=response.data;
resultSet.push(resObj);
})
.catch(function (error) {
console.log("channel error",error.response);
this.setState({channelError:true});
});
})
.catch(function (error) {
console.log("stream error",error.response);
this.setState({streamError:true});
});
})
this.setState({channelList:resultSet});
}
render(){
console.log('this.state',this.state);// ---------a
const {channelList} =this.state;
return(
<div className="container">
{channelList.length>0 &&
<div>
//render stuff here
</div>
}
</div>
);
}
}
ReactDOM.render(
<Twitch />,
document.getElementById('app')
);
API 调用工作正常,我正在获取状态数据。然而,重新渲染没有发生。 console.log(a) 首先返回数组长度 0,扩展时返回适当的长度。
【问题讨论】:
-
您是否在
this.setState({channelList:resultSet});之前检查过resultSet是否为空? -
我向它添加了数据。我在 .then() 上做了 setState 。即使那样它也不起作用
-
那么在resultSet中肯定有数据,但是在setState之后调用的render中this.state是空的?
-
起初它是空的。然后当它展开时有数据
标签: javascript reactjs axios react-dom