javascript - 无法读取反应 js 中未定义的属性“地图”
问题描述
我正在创建选择的自定义组件并面临一些问题。显示此错误无法读取未定义的属性“地图”。我想映射选择选项并在道具页面中使用
function CustomSelect(props) {
const classes = useStyles();
const options = [
"Religion",
"Internal ",
"Not Profit",
];
const {
age,
setAge,
list
} = props;
const handleChange = (event) => {
setAge(event.target.value);
};
return (
<FormControl variant="filled" className={classes.formControl}>
<InputLabel id="demo-simple-select-filled-label">Age</InputLabel>
<Select
labelId="demo-simple-select-filled-label"
id="demo-simple-select-filled"
value={age}
onChange={handleChange}
>
{list.map(item => (
<MenuItem value="test">
{item.options}
</MenuItem>
))}
</Select>
</FormControl>
)
}
解决方案
list
作为道具传递,因此在这种情况下,您可能应该提供默认值。
function CustomSelect(props) {
const classes = useStyles();
const options = [
"Religion",
"Internal ",
"Not Profit",
];
const {
age,
setAge,
list = [], // <-- provide an initial value if undefined
} = props;
const handleChange = (event) => {
setAge(event.target.value);
};
return (
<FormControl variant="filled" className={classes.formControl}>
<InputLabel id="demo-simple-select-filled-label">Age</InputLabel>
<Select
labelId="demo-simple-select-filled-label"
id="demo-simple-select-filled"
value={age}
onChange={handleChange}
>
{list.map(item => (
<MenuItem value="test">
{item.options}
</MenuItem>
))}
</Select>
</FormControl>
)
}
您可能还应该定义 propTypes 以便确保传递正确的类型。
import PropTypes from 'prop-types';
CustomSelect.propTypes = {
list: PropTypes.array.isRequired,
};
如果可以,请尽可能具体
list: PropTypes.arrayOf(PropTypes.shape({
options: PropTypes.string.isRequired,
}))
该.isRequired
位将在非生产版本中引发警告,提示该list
道具未定义或未通过。
推荐阅读
- c# - 我应该处置不属于自己的实例吗?
- winforms - WInform DataGridView 到 Datetimepicker C#
- android - 如何在 Firebase 中显示示例(3 和 7)之间的类别?
- postgresql - 当数据库位于同一 postgres 服务器中时,如何查询两个 postgres 数据库(使用单个查询)?
- angularjs - 使用 ngModel 将 AngularJS 指令升级为 Angular 组件
- spring-webflux - 如何使用 Spring Webflux 创建列表流?
- google-play - Google Play 上的应用提供的订阅产品是否可以在任何地方公开显示?
- amazon-web-services - 实施 AWS Lambda 的首选请求处理程序接口
- javascript - 如何通过 jQuery 替换一段字符串?
- r - 在 *for* 函数中,我可以保持堆叠值吗?