TypeError:无法将未定义或空转换为对象
2019-02-26
2529
我是这里的初学者,我正在使用 udemy 的一些 React 课程,虽然一切都运行良好,我的所有文件都经过我自己和讲师的仔细检查,但此时它抛出了一个我无法弄清楚的错误。
错误如下所示。
6 | const transformedIngredients = Object.keys(props.ingredients)
7 | .map(igKey => {
8 | return [...Array(props.ingredients[igKey])].map((_, i) => {
> 9 | return <BurgerIngredient key={igKey + i} type={igKey} />;
| ^
11 | });
12 | });
burger.js
import React from 'react';
import classes from './Burger.css';
import BurgerIngredient from './BurgerIngredient/BurgerIngredient';
const burger = (props) => {
const transformedIngredients = Object.keys(props.ingredients)
.map(igKey => {
return [...Array(props.ingredients[igKey])].map((_, i) => {
return <BurgerIngredient key={igKey + i} type={igKey} />;
});
});
return (
<div className ={classes.Burger}>
<BurgerIngredient type="bread-top" />
{transformedIngredients}
<BurgerIngredient type="bread-bottom" />
</div>
);
};
export default burger;
代码与讲师相同,但抛出上述错误。
另外两个文件粘贴在下面
burgerbuilder.js
import React, { Component } from 'react';
import Auxy from '../../Hoc/Auxy';
import Burger from '../../components/Burger/Burger';
class BurgerBuilder extends Component {
state = {
ingredients: {
salad: 1,
bacon: 1,
meat: 1,
cheese: 2
}
}
render() {
return (
<Auxy>
<Burger />
<div>Build Controls </div>
</Auxy>
);
}
}
export default BurgerBuilder;
burgeringredient.js
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classes from './BurgerIngredient.css';
class BurgerIngredient extends Component {
render () {
let ingredient = null;
switch (this.props.type){
case ('bread-bottom'):
ingredient = <div className={classes.BreadBottom}></div>;
break;
case ('bread-top'):
ingredient = (
<div className={classes.BreadTop}>
<div className={classes.Seeds1}></div>
<div className={classes.Seeds2}></div>
</div>
);
break;
case ('meat'):
ingredient =<div className={classes.Meat}></div>;
break;
case ('cheese'):
ingredient =<div className={classes.Cheese}></div>;
break;
case ('bacon'):
ingredient =<div className={classes.Bacon}></div>;
break;
case ('salad'):
ingredient =<div className={classes.Salad}></div>;
break;
default:
ingredient =null;
}
return ingredient;
}
}
BurgerIngredient.propTypes={
type: PropTypes.string.isRequired
};
export default BurgerIngredient;
2个回答
遇到了同样的问题!
在 burgerbuilder.js 中确保将原料返回到汉堡组件中:
<Burger ingredients={this.state.ingredients} />
Callum Wallace
2019-04-26
对于遇到此错误的人,还请检查您是否在 BurgerIngredients.js 而不是 BurgerBuilder.js 中声明了您的状态
稍后再感谢我。
akhilesh
2019-10-08