我正在用 React 做電子商務,我收到一個錯誤說
無法讀取未定義的屬性(讀取“地圖”)
這沒有意義,因為我在另一個組件中做了同樣的事情并且它運行良好。
這是我下面的代碼,其中包含對不起作用的地圖功能的評論。如果有什么不清楚的,請告訴我。我檢查了語法錯誤,一切正常
export class CartItem extends Component {
constructor(props) {
super(props);
this.state={
product: {},
failedToLoad: false
}
}
async componentWillMount(){
let data = await this.getProduct(this.props.product.itemId);
// let product = data.data.product;
// this.setState({product: product});
if (data.data.product) {
this.setState({product: data.data.product});
} else {
this.setState({failedToLoad: true});
}
}
async getProduct(id){
return await fetchTheQuery(
`query getProduct($id: String!){
product(id: $id){
name
prices{
currency
amount
}
}
}`, {id: id}
)
}
render() {
const {addProduct, productsToPurchase} = this.props.cartContext
const {selectedCurrency} = this.props.currencyContext
console.log(this.state.product.prices)
let productFetched = this.state.product
if (this.state.failedToLoad){
return (<div>Something went wrong</div>)
}
else if (productFetched){
return(
<div>
<h2> {this.state.product.name} </h2>
<h5>
{/*There is an error here*/}
{ this.state.product.prices.map(
price =>{
if (price.currency == selectedCurrency){
return( <> { getSymbolFromCurrency(selectedCurrency) " " price.amount }</> )
}
}
)}
</h5>
<button onClick={() => {
addProduct(this.props.product.itemId, this.state.product.prices)
}}> Add </button>
<h4>{productsToPurchase[this.props.itemIndex].qty}</h4>
<hr/>
</div>
)
}
else {
return <p>Loading............</p>
}
}
}
uj5u.com熱心網友回復:
您需要檢查this.state.product.prices物件中是否存在 。您收到此錯誤是因為在第一次渲染期間集合為空。
{ this.state.product.prices
&& this.state.product.prices.map(
price =>{
if (price.currency == selectedCurrency){
return(
<>
{
getSymbolFromCurrency(selectedCurrency) " " price.amount }.
</> )
}
}
)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/357430.html
標籤:javascript 反应 反应上下文 映射函数
