【发布时间】:2019-02-17 02:46:24
【问题描述】:
我正在尝试在购物车中显示商品。我制作了一个“BagItem”组件来显示有关该项目的信息,该信息来自一个处于状态的购物车数组中的对象,在 redux 中。我还制作了一个“Bag”组件,用于映射购物车信息并返回“BagItem”组件。
一切似乎都在使用地图功能。当我 console.log 记录 BagItem 组件中的信息时,我看到了我需要显示的所有属性。问题是在 Bag Component 中, BagItem 组件不会渲染。加载网页时,我看到 StoreNav 和小计文本,但 BagItem 组件不显示。
我对 React 很陌生,我确信我缺少一些明显的东西。我整天都在努力解决这个问题,如果您能提供任何帮助,我将不胜感激。
袋子组件:
import React, { Component } from "react";
import { connect } from "react-redux";
import StoreNav from "../store/StoreNav";
import BagItem from "../bag/BagItem";
import { getCart } from "../../ducks/reducer";
class Bag extends Component {
constructor(props) {
super(props);
this.state={}
}
componentDidMount(){
this.props.getCart()
console.log(this.props.cart)
}
componentDidUpdate(){
this.props.getCart()
}
render() {
const bagList =
this.props.cart && this.props.cart.map(element => {
console.log(this.props.cart)
return <BagItem
element={element}
id={element.id}
key= {`${element.id}${element.name}${element.price}${element.image}${element.size}${element.sleeves}${element.fabric}${element.length}`}
name={element.name}
image={element.image}
size={element.size}
price={element.price}
sleeves={element.sleeves}
fabric={element.fabric}
length={element.length}
/>
})
return (
<div>
<StoreNav />
{bagList}
<p>Subtotal</p>
</div>
);
}
}
const mapStateToProps = state => {
return {
cart: state.cart
};
};
export default connect(
mapStateToProps,
{ getCart: getCart }
)(Bag);
BAGITEM 组件
import React, { Component } from "react";
import { connect } from "react-redux";
import "./bagitem.css";
import { getCart } from "../../ducks/reducer";
class BagItem extends Component {
componentDidMount(){
this.props.getCart()
console.log(this.props.cart[0][0].name)
}
render() {
return (
<div className="bag-item-component-container">
<div className="bag-item-component">
<div className="bag-item-row1">
<div>Size</div>
<div>Quantity</div>
<div>Price</div>
<div>Remove</div>
</div>
{/* <div className="bag-item-row2">
placeholder
</div> */}
<div className="bag-item-image-and-details-container">
<div className="img1">
<img className="item-image" alt="" src={this.props.cart[0][0].image} />
</div>
<div>{this.props.cart[0][0].name}
<div className="details">
<div>sleeves</div>
<div>length</div>
<div>fabric</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
cart: state.cart
};
};
export default connect(
mapStateToProps,
{ getCart: getCart }
)(BagItem);
【问题讨论】:
-
一个明显的事情是你没有调用
{bagList}- 更改为{bagList()},还将该函数移到render()方法之外...... -
this.props.getCart()会触发重新渲染吗? -
另外,使用
react-devtools扩展来查看在您的应用中呈现的内容。 -
我检查了 react-devtools 并且 BagItem 组件没有被渲染。 StoreNav 和小计之间没有任何内容。我会看看是否可以确定 this.props.getCart 是否正在重新渲染。
标签: reactjs