Javascript 无法读取react js中未定义的属性“map”
我正在创建select的自定义组件,并面临一些问题。 显示此错误无法读取未定义的属性“map”。 我想映射选择选项并在道具页面中使用Javascript 无法读取react js中未定义的属性“map”,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在创建select的自定义组件,并面临一些问题。 显示此错误无法读取未定义的属性“map”。 我想映射选择选项并在道具页面中使用 function CustomSelect(props) { const classes = useStyles(); const options = [ "Religion", "Internal ", "Not Profit", ]; const {
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>
)
}
列表是作为道具传递的,所以在这种情况下,您可能应该提供一个默认值
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>
)
}
如果可以,请尽可能具体
list: PropTypes.arrayOf(PropTypes.shape({
options: PropTypes.string.isRequired,
}))
.isRequired位将在非生产版本中抛出一条警告,指出列表属性未定义或未传递。是否从父组件以数组形式传递列表?能否显示列表数组?是的,此错误已解决,以感谢您。但选项数组不在映射中list@TusharKumawat能否提供item.options对象形状是什么?i、 你想用它呈现什么?
list: PropTypes.arrayOf(PropTypes.shape({
options: PropTypes.string.isRequired,
}))