无法读取 React js 中未定义的属性“map”
2020-07-17
3024
我正在创建 select 的自定义组件,但遇到了一些问题。 显示此错误无法读取未定义的属性“map”。 我想映射 select 选项并在 props 页面中使用
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>
)
}
1个回答
list
作为 prop 传递,因此在这种情况下您可能应该提供一个默认值。
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
prop 未定义或
未
传递。
Drew Reese
2020-07-17