javascript - 遍历一个对象,并为对象中的每个属性返回一个组件
问题描述
大家好,我是新手,我构建了组件-我有一个用户偏好状态-我确实检查了所有偏好,并在 mui 的帮助下返回了他对每个偏好的评分-我一直在尝试几个小时才能做到这一点,我做不到。
这是我编写的代码,它运行但我没有取回组件,我不明白为什么。
import React, { Component, Fragment } from 'react';
// MUI stuff
import Rating from '@material-ui/lab/Rating';
// Icons
import ListIcon from '@material-ui/icons/List';
class Profile extends Component {
constructor(props) {
super(props);
this.state =
{preferences: {
html: "5",
react: "4",
css: "4",
angular: "3",
}};
}
render() {
let profilePreferences = {preferences && (
<Fragment>
<ListIcon color="primary" />
<hr />
{
Object.keys(preferences).map(prefer => {<Rating name={prefer} defaultValue={parseInt(preferences[prefer], base)} precision={1} readOnly/>})
}
<hr />
</Fragment>
)}
return profilePreferences ;
}
}
export default Profile;
我认为问题很小,但我找不到它,我只想检查我的对象并为每个功能返回“materialUi”的“评级”组件。
解决方案
目前,preferences
未定义。你需要从this.state
.
render() {
const { preferences } = this.state; // <------ Add this line
let profilePreferences = {preferences && (
<Fragment>
<ListIcon color="primary" />
<hr />
{
Object.keys(preferences).map(prefer => (<Rating name={prefer} defaultValue={parseInt(preferences[prefer], base)} precision={1} readOnly/>))
}
<hr />
</Fragment>
)}
return profilePreferences ;
}
推荐阅读
- npm - 尝试在 siemens iot2040 上安装 node-red 时,npm 读取 ECONNREST 错误
- nginx - 在 Ingress 中添加 allow-http 配置后未禁用 HTTP
- amazon-web-services - 如何将 AWS API Gateway REST API 导出到文件?
- mongodb - Mongoose findOneAndUpdate 用于更新文档中的多个字段
- javascript - 从 - new Date().getTime() 获取时间;
- javascript - 在 React 中使用 localStorage
- google-sheets - 对于每个额外的“x”,添加“y”
- android-fragments - 如何从一个活动转移到一个片段?
- python - 在同一位置的 Django 视图中调用单独的 Python 脚本
- google-apps-script - 如何获取并发送到提交的最后一行?