gpt4 book ai didi

javascript - 为什么 this.props.map 不是一个函数?

转载 作者:行者123 更新时间:2023-12-02 22:14:26 25 4
gpt4 key购买 nike

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 is not a function.

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

最佳答案

在 React 中,props 始终是一个对象

当您尝试将数组分配给defaultProps时,该数组将转换为对象。所以 this.props.map不是一个函数

您可以注释错误行,然后添加{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>

关于javascript - 为什么 this.props.map 不是一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com