无法读取React JS中未定义的属性'map'

时间:2020-07-17 07:06:26

标签: javascript reactjs react-native

我正在创建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>
  )
}

1 个答案:

答案 0 :(得分:2)

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

Typechecking with PropTypes

import PropTypes from 'prop-types';

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

如果可以的话,请尽可能具体

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

在非生产版本中,.isRequired位将引发警告,说明list道具未定义,否则将通过 。< / p>