React.JS处理未定义道具的最佳方法是什么

时间:2019-01-09 01:21:03

标签: reactjs

我正在学习React.JS。我正在将对象数组传递给“ AlbumContainer”,但是“ this.props.albums [0] .name_combined”未定义。处理此问题的最佳方法是什么。预先非常感谢。

class AlbumContainer extends React.Component {
    render() {
        const divStyle = {
            margin: '0px',
            border: '1px solid pink',
            color: 'blue',
            overflow: 'auto'
        };

        return (
            <div>
                <div>
                    {this.props.albums[0].name_combined}
                </div>
                <div style={divStyle}>
                    SOME TEXT
                </div>
            </div>
        );
    }
}

1 个答案:

答案 0 :(得分:1)

最安全的做法是执行以下操作

{ this.props.albums && this.props.albums[0] && 
this.props.albums[0].name_combined ? this.props.albums[0].name_combined : '' }
相关问题