0
下面的代碼:發生反應,渲染狀態變化
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,並在展開時返回適當的長度。
你檢查了'result.set'是否在'this.setState({channelList:resultSet})之前是空的嗎? –
我向它添加了數據。我在.then()上做了setState。即使那麼它不起作用 – DroidNoob
因此,resultSet中肯定有數據,但是在setState後調用的render中,this.state爲空? – paqash