如何映射对象数组,以使用新键返回对象数组

时间:2019-03-24 16:27:51

标签: reactjs

我正在尝试呈现数组对象,但是我的代码仅呈现一个对象,并在尝试添加多个对象时引发错误。

如果我尝试添加另一个问题集,则会引发以下错误:第16行:解析错误:意外的令牌

  14 |     c: "Trump"
  15 |   },
> 16 |   {
     |   ^
  17 |     question: "Who is the president of America?",
  18 |     answers: {
  19 |       a: "Buhari",

代码:

constructor(props){
super(props);
questions =  [
{
  question: "Who is the president of America?",
  answers: {
    a: "Buhari",
    b: "Putin",
    c: "Trump"
  },

}         
];
this.state = {
    question : [],
};
}

handleQuestion(){ 
  this.setState({
  question: questions
});    
}
render(){    
  return (    
      <div className = "container">
      <button type="button" onClick={()=>this.handleQuestion()}>
        Show Question
      </button>   

      <ul>
        {this.state.question.map((data,i)=>(

            <li key={i}>{data.question}       
              <div>a : {data.answers.a}</div>
              <div>b : {data.answers.b}</div>
              <div>c : {data.answers.c}</div>
            </li>

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

 export default App;

2 个答案:

答案 0 :(得分:1)

您尚未在构造函数中正确定义问题数组,要么必须使用constvarlet之类的关键字来定义它们,要么将其定义为{{1 }}。查看您的情况,如果要将其定义为类成员,则应将其定义为类实例属性,否则可以在类范围之外将其声明为全局变量

class instane property

答案 1 :(得分:0)

您应该在构造函数内部设置默认状态。

this.state = {
question: [
   {
   question: "Who is the president of America?",
   answers: {
    a: "Buhari",
    b: "Putin",
    c: "Trump"
   }
]
}

如果要保留为空。您应该使用hasOwnProperty来确保对象在渲染之前存在

相关问题