React Typescript音乐播放器项目笔记:4、异步获取数据&保存组件状态

19 篇文章 0 订阅
17 篇文章 0 订阅

项目地址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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值