javascript - 为什么 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
方法不起作用?
解决方案
在反应中,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>
推荐阅读
- c# - 没有添加到提交但存在未跟踪的文件
- git - 何时从标签创建分支?
- jquery - Fullcalendar - 如何获取点击事件的位置
- javascript - 尝试使用数据表和 javascript 在显示页面上显示发布数据
- tomcat - Tomcat版本冲突以及apache 7.35和windows 10的兼容性问题
- react-native - 在调用函数上设置输入值 - React Native
- ruby - Ruby - Capybara - ArgumentError:无效键
- c++ - 如何修复 OpenCL 冻结?
- node.js - 重定向非 www 和 http - NodeJS 和 Express
- vue.js - Math.round() 作为 v-model 返回值