如何在JSX中访问嵌套数组

时间:2017-06-14 23:22:48

标签: javascript json react-redux react-jsx

我是新的react-redux应用程序。我试图制作一个酒单,根据服务器(wines.json)的json文件中的平均星数显示排名(x中的5星)。在我的Wines.jsx文件中,我从{wine.name}{wine.vintage}等葡萄酒中渲染了一些json类别,但是当我尝试渲染{wine.ratings}时,我将此错误发送到控制台:

Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {stars}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of {葡萄酒{1}}

似乎因为在wines.json文件中,'rating'包含由'star'对象组成的嵌套数组,.不会呈现。我该怎么做才能获得对这些数据的访问权?

wines.json:

{wine.ratings}

wines.jsx:

"wines": [{
"id": "f2ca57a5-d9da-4808-9164-8d6e0da0aef5",
"name": "Apothic Red",
"vintage": "2015",
"vineyard": "Apothic",
"type": "Red Blend",
"region": "California",
"unitsSold": 51,
"ratings": [{
  "stars": 5
}, {
  "stars": 3
}]
  }...

wineActions.js:

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';

import * as actionCreators from './wineActions';

import './wines.scss';
import { SplitButton } from 'react-bootstrap';
import './ratings';


export class Wines extends Component {
  componentDidMount() {
    this.props.actions.fetchWines();
  }

  render() {
    return (
      <div className="wines">
        <row>
          <h1 className="wines__title" >Wine List</h1>
        </row>
        <row>
          <SplitButton title="Select Year"></SplitButton>
        </row>  
        <ul className="wines__list">
          {
            this.props.wines
              .map(wine => 
                <div key={wine.id}>

                      <div className='divLeft'>
                        <img src='front-end-challenge--provo17/client/wines/wine-placeholder.png' />
                      </div>

                      <div className='divRight'>
                        <h3>{wine.name}, {wine.vintage}</h3>
                        <br />
                        <p>{wine.type}</p>
                        <span>{wine.ratings}</span>
                        <p>({wine.unitsSold})</p>
                      </div>

                      <hr />

                </div>)
          }
        </ul>
      </div>
    );
  }
}



// React.render(<FormComponent />, document.getElementById('star-rating'));

Wines.propTypes = {
  wines: PropTypes.array,
  actions: PropTypes.object
};

function mapStateToProps(state) {
  return {
    ...state.wines
  };
}

function mapDispatchToProps(dispatch) {
  return { actions: bindActionCreators(actionCreators, dispatch) };
}

    export default connect(mapStateToProps, mapDispatchToProps)(Wines);

1 个答案:

答案 0 :(得分:0)

ratings是一个对象数组,并且对象无效,因为错误消息显示为儿童。您可以映射到评级数组,就像您通过葡萄酒阵列进行映射一样。您还需要提供密钥。通常你会使用ID,但你的评级没有id。虽然不太好,但可以使用数组索引作为键。

而不是<span>wine.ratings</span><span>{wine.ratings.map((rating,indx) => <span key={indx}>{rating.stars}</span>)}</span>