防止状态中的空嵌套数组

时间:2017-06-15 00:52:47

标签: javascript reactjs redux react-redux

我现在有一个小的反应redux应用程序,我正在添加电影,并在我的对象中添加图像作为嵌套数组。

添加项目后我的状态是什么

{
  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渲染块中解决此问题?

感谢您的帮助

1 个答案:

答案 0 :(得分: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,然后执行地图。否则它什么都不会。