[英]Cannot read property 'map' of undefined in react js
我正在創建 select 的自定義組件並面臨一些問題。 顯示此錯誤無法讀取未定義的屬性“地圖”。 我想 map select 選項並在道具頁面中使用
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
道具未定義或未通過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.