首页 > 解决方案 > 无法读取反应 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>
  )
}

标签: javascriptreactjsreact-native

解决方案


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 以便确保传递正确的类型。

使用 PropTypes 进行类型检查

import PropTypes from 'prop-types';

CustomSelect.propTypes = {
  list: PropTypes.array.isRequired,
};

如果可以,请尽可能具体

list: PropTypes.arrayOf(PropTypes.shape({
  options: PropTypes.string.isRequired,
}))

.isRequired位将在非生产版本中引发警告,提示该list道具未定义或未通过


推荐阅读