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;
解决方案
您没有在构造函数中正确定义问题数组您必须使用关键字,如,const
来定义它们,或者将其定义为. 查看您的案例,如果要将其定义为类成员,则应将其定义为类实例属性,否则您可以在类范围之外将其声明为全局变量var
let
class 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;
推荐阅读
- git - 确保 git pull 总是覆盖一个特定的本地文件的方法
- c - 有人可以解释我如何打开一个文件(包含一个数字列表)然后通过我的选择排序算法传递它们吗?
- python - 用 Python 求两个多项式之和
- angular - 通过 ngx-cookieconsent 删除 cookie
- javascript - 我如何将不同变量的多个不同值从 popup.js 发送到 inject.js 以便可以在 inject.js 脚本中使用?
- android - 错误:包 android.view 不存在
- javascript - 调用插件方法在 jQuery 中动态添加元素到 DOM
- python - 使用 Kivy/Buildozer 后应用程序无法运行
- wpf - 使用 TextBlock 扩展的 WPF TextBlock 绑定到 ViewModel 不起作用
- python - 强制覆盖 PySimpleGUI 窗口