在React中映射对象数组 - 意外标记

时间:2017-10-03 10:45:13

标签: arrays reactjs ecmascript-6 jsx

我有一组像这样的对象:

{
_id: "59d2a245734d1d42e49ed55d",
pollName: "Favourite Colour",
createdBy: "John",
pollData: [
    {key: "blue", value: 5},
    {key: "green", value: 7},
    {key: "red", value: 4},
    {key: "orange",value: 1}
    ]
},
{
_id: "59d2a291734d1d42e49ed574",
pollName: "Favourite Ice Cream",
createdBy: "Peter",
pollData: [
    {key: "Chocolate", value: 12},
    {key: "Vanilla", value: 7},
    {key: "Strawberry", value: 10}
    ]
}

我正在尝试将这些映射到饼图,但会出现语法错误。这是React中的代码:

render() {
    const {polls} = this.state

    return(

        <h1>Home</h1>

        {polls.map((poll, index) => (
            <div key={poll._id}>
                <Chart poll={poll} />
            </div>
        ))}

    )
}

我得到的错误信息在开头括号上:

  

意外的令牌,预期,

     
    

{polls.map((poll,index)=&gt;(

  

我之前在另一个项目上完成了这项工作,它通过一组对象进行了精确的映射,然后将每个对象传递给一个组件。为什么在这种情况下不起作用?

2 个答案:

答案 0 :(得分:0)

应该有大括号而不是&#34;()&#34;

    {polls.map((poll, index) => { 
     return <div key={poll._id}>
                <Chart poll={poll} />
            </div>  }

答案 1 :(得分:0)

&#13;
&#13;
const polls = [
  {
    _id: "59d2a245734d1d42e49ed55d",
    pollName: "Favourite Colour",
    createdBy: "John",
    pollData: [
      {key: "blue", value: 5},
      {key: "green", value: 7},
      {key: "red", value: 4},
      {key: "orange",value: 1}
    ]
  },
  {
    _id: "59d2a291734d1d42e49ed574",
    pollName: "Favourite Ice Cream",
    createdBy: "Peter",
    pollData: [
      {key: "Chocolate", value: 12},
      {key: "Vanilla", value: 7},
      {key: "Strawberry", value: 10}
    ]
  }
];


polls.map((poll, index) => {
  console.log(poll._id, poll.pollData)
});
&#13;
&#13;
&#13;