简体   繁体   English

无法读取反应 js 中未定义的属性“地图”

[英]Cannot read property 'map' of undefined in react js

I am creating custom components of select and facing some issues.我正在创建 select 的自定义组件并面临一些问题。 Showing this error Cannot read property 'map' of undefined.显示此错误无法读取未定义的属性“地图”。 I want to map select option and use in pages from props我想 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 is passed as a prop, so in this situation you should probably provide a default value. 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>
  )
}

You should probably also define propTypes so you can ensure the correct type is passed.您可能还应该定义 propTypes 以便确保传递正确的类型。

Typechecking with PropTypes使用 PropTypes 进行类型检查

import PropTypes from 'prop-types';

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

If you can, be as specific as possible如果可以,请尽可能具体

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

The .isRequired bit will throw a warning in non-production builds that the list prop is undefined or otherwise not been passed. .isRequired位将在非生产版本中引发警告,表明list道具未定义或未通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM