首页 > 解决方案 > 为什么 this.props.map 不是函数?

问题描述

class Pokedex extends Component {
    static defaultProps =
    [
        {id: 4, name: 'Charmander', type: 'fire', base_experience: 62},
        {id: 7, name: 'Squirtle', type: 'water', base_experience: 63},
        {id: 11, name: 'Metapod', type: 'bug', base_experience: 72},
        {id: 12, name: 'Butterfree', type: 'flying', base_experience: 178},
        {id: 25, name: 'Pikachu', type: 'electric', base_experience: 112},
        {id: 39, name: 'Jigglypuff', type: 'normal', base_experience: 95},
        {id: 94, name: 'Gengar', type: 'poison', base_experience: 225},
        {id: 133, name: 'Eevee', type: 'normal', base_experience: 65},
    ];
    render(){
        return(
            <div className="Pokedex">
                <h1>Pokedex</h1>
                {this.props.map((item) => {return <Pokecard {...item} />})};


            </div>
        )
    }
}

export default Pokedex;

这是我的代码,我得到了错误:

TypeError:this.props.map 不是函数。

我的 defaultProps 不是数组吗?为什么该map方法不起作用?

标签: javascriptreactjs

解决方案


在反应中,props always is an object.

当您尝试将数组分配给 defaultProps 时,该数组将为converted to object. this.props.map也会not be a function。_

您可以注释错误行,然后添加{JSON.stringify(this.props)}

class Pokedex extends React.Component {
  static defaultProps = [
    { id: 4, name: 'Charmander', type: 'fire', base_experience: 62 },
    { id: 7, name: 'Squirtle', type: 'water', base_experience: 63 },
    { id: 11, name: 'Metapod', type: 'bug', base_experience: 72 },
    { id: 12, name: 'Butterfree', type: 'flying', base_experience: 178 },
    { id: 25, name: 'Pikachu', type: 'electric', base_experience: 112 },
    { id: 39, name: 'Jigglypuff', type: 'normal', base_experience: 95 },
    { id: 94, name: 'Gengar', type: 'poison', base_experience: 225 },
    { id: 133, name: 'Eevee', type: 'normal', base_experience: 65 }
  ]
  render () {
    return (
      <div className='Pokedex'>
        <h1>Pokedex</h1>
        {/*this.props.map((item) => {return <Pokecard {...item} />})*/}
        {JSON.stringify(this.props)}
      </div>
    )
  }
}

ReactDOM.render(<Pokedex />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<body>
  <div id="root"></div>
</body>


推荐阅读