鍍金池/ 問(wèn)答/HTML/ 初學(xué)react,怎么優(yōu)化這段代碼,能不能幫忙改一下

初學(xué)react,怎么優(yōu)化這段代碼,能不能幫忙改一下

componentWillReceiveProps =(newProps)=> {

        const _self = this;
        //console.log('基本信息組件接受參數(shù)');
        //console.log('newProps = ', newProps['basicInformationData']);
        let videoLength = 0;
        let videoSize = 0;
        let distanceCreationTime = 0;

        let tags = []

        if( newProps['basicInformationData'] !== undefined) {
            if ( newProps['basicInformationData']['distance_time'] !== undefined ) {
                distanceCreationTime = newProps['basicInformationData']['distance_time']
            }

            if ( newProps['basicInformationData']['duration'] !== undefined ) {
                videoLength = newProps['basicInformationData']['duration']
            }

            if ( newProps['basicInformationData']['size'] !== undefined ) {
                videoSize = newProps['basicInformationData']['size']
            }

            if ( newProps['basicInformationData']['tags'] !== undefined ) {
                tags = newProps['basicInformationData']['tags']
            }
        }

        _self.setState({
            tags: tags, // 任務(wù)所有名稱
            videoLength: videoLength,
            videoSize: videoSize,
            distanceCreationTime: distanceCreationTime
        })


    }

下面這段怎么優(yōu)化?

_self.setState({
            tags: tags, // 任務(wù)所有名稱
            videoLength: videoLength,
            videoSize: videoSize,
            distanceCreationTime: distanceCreationTime
        })

這個(gè)if怎么優(yōu)化

if( newProps['basicInformationData'] !== undefined) {
            if ( newProps['basicInformationData']['distance_time'] !== undefined ) {
                distanceCreationTime = newProps['basicInformationData']['distance_time']
            }

            if ( newProps['basicInformationData']['duration'] !== undefined ) {
                videoLength = newProps['basicInformationData']['duration']
            }

            if ( newProps['basicInformationData']['size'] !== undefined ) {
                videoSize = newProps['basicInformationData']['size']
            }

            if ( newProps['basicInformationData']['tags'] !== undefined ) {
                tags = newProps['basicInformationData']['tags']
            }
        }
回答
編輯回答
假灑脫
const obj = newProps['basicInformationData'] || {}
let distanceCreationTime = obj['distance_time'] || 0;
let videoSize = obj['size'] || 0;
let videoLength =  obj['duration'] || 0;
let tags = obj['tags'] || []
2017年1月31日 23:37