在之前的帖子中,我试图自己解决这个错误,但没有成功。我正试着把";state.配料";财产(我想(,我说的是";糖"咖啡"水";等我得到这个错误:
类型错误:无法将未定义或null转换为对象这是CoffeeBuilder.js代码的重要部分:
const ingPrices = {
sugar: 0,
coffee: 0.2,
water: 0,
milk: 0.2,
};
class CoffeeBuilder extends Component {
constructor(props) {
super(props);
this.state = {
ingredients: {
sugar: 0,
coffee: 0,
water: 0,
milk: 0,
},
totalPrice: 0,
purchasing: false,
};
}
addIngHandler = (type) => {
const newCount = this.state.ingredients[type] + 1;
console.log("clicked");
const updatedIng = { ...this.state.ingredients };
updatedIng[type] = newCount;
const ING_PRICE = ingPrices[type];
const oldPrice = this.state.totalPrice;
this.setState({
totalPrice: oldPrice + ING_PRICE,
ingredients: newCount,
});
};
render() {
return (
<div>
<CoffeeSlider />
<CoffeeControls addIng={this.addIngHandler} removeIng={this.removeIngHandler} />
<OrderSummary ingredients={this.state.ingredients} price={this.state.totalPrice} />
</div>
);
}
}
export default CoffeeBuilder;
这是OrderSummary.js代码:
import React from "react";
import "./OrderSummary.css";
const OrderSummary = (props) => {
return Object.keys(props.ingredients).map((igKey) => {
console.log(igKey);
return (
<div>
<li key={igKey}>
<span style={{ textTransform: "capitalize" }}>{igKey}</span>:
{props.ingredients[igKey]}
</li>
</div>
);
});
};
export default OrderSummary;
console.log可以很好地获取数据,但当我试图将其作为列表在跨度中返回时,它会出错。
请尝试这样的CoffeBuilder组件,您的代码有一些问题,例如状态没有在构造函数中声明,没有呈现函数。
下面是代码沙盒链接:
https://codesandbox.io/s/frosty-mountain-235yk?file=/src/App.js
class CoffeeBuilder extends Component {
constructor(props) {
super(props);
this.state = {
ingredients: {
sugar: 0,
coffee: 0,
water: 0,
milk: 0,
},
totalPrice: 0,
purchasing: false,
}
}
render() {
return ( < OrderSummary ingredients = {
this.state.ingredients
}
/>);
}
}