项目地址:https://github.com/BUPTlhuanyu/react-music-lhy
面包屑选择页面内容的时候,当推荐页面对应的组件有异步加载未完成的时候,切换到歌手页面,推荐页面组件被卸载,异步加载完成需要setState,此时将会报错:因为组件被卸载无法显示更新后的state。因此组件卸载的时候设置一个标志位unmoutedFlag,并且在setState的时候判断该标志位决定是否setState。
切换页面并重新切回来的时候,组件componentDidMount中会重新获取异步数据,因此额外增加了请求,因此在componentWillUnmount中可以缓存已经获取的数据,下次加载的时候判断数据是否存在。
interface hotType{
title:string,
items:Array<any>
}
class mapType {
hot:hotType;
[index: string]: hotType;
constructor(hotName:string){
this.hot={
title:hotName,
items:[]
}
}
}
...
interface singerState{
singers: Array<any>
}
let cacheData:{
singers: Array<any>
};
class Singer extends Component<singerProps, singerState>{
unmoutedFlag:boolean
constructor(props: singerProps){
super(props);
this.unmoutedFlag=false
this.state = {
singers: []
}
}
componentDidMount(){
if(cacheData){
this.setState({
singers: cacheData.singers,
})
}else{
this._getSingerList()
}
}
componentWillUnmount(){
cacheData = {
singers:this.state.singers
}
this.unmoutedFlag=true
}
_getSingerList() {
getSingerList().then((res) => {
if (res.code === ERR_OK && !this.unmoutedFlag) {
this.setState({
singers: this._normalizeSinger(res.data.list)
})
}
})
}
_normalizeSinger(list:Array<any>) {
...
}
render(){
const {singers} = this.state
return(
<div className="singer">
<ListView data={singers}/>
<Route path="/singer/:id" component={SingerDetail}/>
</div>
)
}
}
export default Singer