以下是代码:
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,并在扩展时返回适当的长度。
答案 0 :(得分:0)
我解决了。
事实证明shouldComponentUpdate
返回错误并且不让重新发生。
我删除了那个方法。现在它工作正常