2017-06-15 56 views
0

我目前有一個小反應的REDX應用程序,我添加電影,並添加圖像作爲我的對象內嵌套數組。防止在狀態爲空的嵌套數組

什麼我的狀態看起來像添加一項

{ 
    movies: [ 
    0:{ 
    "title": "asda", 
    "director": "asda", 
    "genre": "asd", 
    "description": "asd", 
    "images": [ 
     { 
     "name": "george-michael-306600-2-raw.jpg", 
     "type": "image/jpeg", 
     "size": "65 kB", 
     "base64": "data:image/jpeg;base64,/9j/IMAGE//Z", 
     "file": {} 
     } 
    ], 
    "id": "ae04f1e8-18bb-434b-a3e3-b02d44e68d2a" 
    } 
} 

然後我呈現在我的組件如下

import React from 'react' 
import Slider from 'react-slick' 
import { dispatch, connect } from 'react-redux' 
import {Icon} from 'react-fa' 
import { deleteMovie } from '../../actions/movieActions' 

import 'slick-carousel/slick/slick.css' 
import 'slick-carousel/slick/slick-theme.css' 
import './MovieList.scss' 

class MovieList extends React.Component{ 
    constructor(props){ 
    super (props) 
    } 

    handleClick(id) { 
    dispatch(deleteMovie(id)) 
    } 

    render() { 
    // Settings for slick-carousel 
    let settings = { 
     infinite: true, 
     speed: 500 
    } 


    return (
     <div className='col-lg-12'> 
     {this.props.movies.map((b, i) => 
      <div key={i} className="col-lg-2"> 
      <Slider {...settings}> 
       {b.images.map((b, z) => 
       <div className="img-wrapper"> 
        <Icon name="trash" className="trash-icon" onClick={(e) => 
        console.log(this.props.movies[i].id), 
        this.props.onMovieClick.bind(this.props.movies[i].id) 
        }/> 
        <img className="img-responsive" key={z} src={b.base64}></img> 
       </div> 
      )} 
      </Slider> 
      <div className="text-left info"> 
       <h2>{b.title}</h2> 
       <p>{b.genre}</p> 
      </div> 
      </div> 
     )} 
     </div> 
    ) 
    } 
} 

// map state from store to props 
const mapStateToProps = (state) => { 
    return { 
    movies: state.movies 
    } 
}; 

// Map actions to props 
const mapDispatchToProps = (dispatch) => { 
    return { 
    onMovieClick: (id) => { 
     dispatch(deleteMovie(id)) 
    } 
    } 
} 

export default connect(mapStateToProps, mapDispatchToProps)(MovieList) 

現在這工作完全找到和我的項目呈現爲後打算直到,我試圖過濾(刪除)一個項目,然後我的內部循環,使圖像進入滑塊{b.images.map((b, z)失敗,我得到一個錯誤

Cannot read property 'map' of undefined

我怎樣才能保護這個內環從爲了顯示項目,如果數組爲空/未定義?

在常規JS中,我只是簡單地將地圖調用包裹在一張支票中,以查看圖像是否未定義,但是如何在JSX渲染塊中解決此問題?

感謝您的幫助

回答

2

爲了防止它,你可以做地圖像在此之前使用存在確認:

{b.images && b.images.map((b, z) => 
    <div className="img-wrapper"> 
     <Icon name="trash" className="trash-icon" onClick={(e) => 
      console.log(this.props.movies[i].id), 
      this.props.onMovieClick.bind(this.props.movies[i].id) 
     }/> 
     <img className="img-responsive" key={z} src={b.base64}></img> 
    </div> 
)} 

b.images會檢查是否b.images定義,然後做圖。否則它不會呈現任何內容。

+0

非常感謝你的幫助人 –

+0

你是相當受歡迎的 –