首页 > 解决方案 > 如何映射对象数组,以返回具有新键的对象数组

问题描述

我正在尝试渲染数组对象,但是当我尝试添加多个对象时,我的代码只渲染一个对象并引发错误。

如果我尝试添加另一个问题集,则会引发以下错误:第 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;

标签: reactjs

解决方案


您没有在构造函数中正确定义问题数组您必须使用关键字,如,const来定义它们,或者将其定义为. 查看您的案例,如果要将其定义为类成员,则应将其定义为类实例属性,否则您可以在类范围之外将其声明为全局变量varletclass instane property

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

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

      handleQuestion(){ 
        this.setState({
        question: this.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;

推荐阅读