【发布时间】:2018-08-08 19:31:05
【问题描述】:
当购物车项目视图展开时,所有其他购物车项目视图都需要折叠。问题是我的项目视图是一个单独的组件,需要将此信息从父级传递给它。单击箭头时,项目 id 从子组件传递回父组件,然后传递到操作,最后传递到应用程序状态更新的减速器。这会触发父组件中的重新渲染,但这不会渗透到需要它的子组件,即使已更改的属性正在传递给子组件。有谁知道谁来获取此应用程序状态更改以导致子组件重新渲染?
这是我的购物车项目视图(子组件)。 isExpanded 变量需要从应用状态更改中更新,以控制哪些视图应该展开和折叠。
componentWillReceiveProps(nextProps) {
console.log('nextProps: ', nextProps)
}
render() {
const serverUrl = getServerAddress();
const {product} = this.props;
const price = product.iogmodPrice ? product.iogmodPrice : product.price;
const isExpanded = this.props.expandedViewId === product.id;
const imageSrc = product.imageName
? 'https://b2b.martinsmart.com/productimages/'+ product.imageName.replace("Original", "Thumbnail")
: serverUrl + '/b2b/resources/images/nophoto.gif';
return (
<View style={styles.pContainer}>
<CartProduct
imageName={imageSrc}
name={product.description}
itemNum={product.id}
price={price}
pack={product.pack}
averageWeight={product.averageWeight}
cases={product.order_count}
/>
<TouchableOpacity style={styles.buttonContainer} onPress={() => this.props.onExpandClick(product.id)}>
{isExpanded ? <LineIcon name="arrow-up" style={styles.arrowIcon} /> : <LineIcon name="arrow-down" style={styles.arrowIcon} />}
</TouchableOpacity>
{isExpanded &&
<ExpandHeightView height={70}>
<View style={styles.counterContainerView}>
<QuantityCounter style={{width: '100%'}} product={product} />
</View>
</ExpandHeightView>
}
</View>
);
}
当单击展开箭头时,项目 ID 被传回并发送到操作(父视图):
expandAndCollapseItems = (id) => {
this.props.dispatch(collapseCartItemViews(id));
}
父组件的渲染线:
render() {
const {isLoading, displayDetails, sortCasesAsc, details, items, expandedItem} = this.props.orderInfo;
这里是被点击(被展开)的项目被传入的地方:
<FlatList
data={items}
keyExtractor={(item, index) => item.id.toString()}
renderItem={({item}) => <CartProductItem product={item} expandedViewId={expandedItem} onExpandClick={(id) => this.expandAndCollapseItems(id)} />}
/>
购物车动作功能:
export function collapseCartItemViews(id) {
return (dispatch, getState) => {
dispatch({
type: types.SET_EXPANDED_STATE,
id: id
});
}
}
reducer 函数:
case types.SET_EXPANDED_STATE:
const id = action.id;
return {
...state,
expandedItem: id
}
【问题讨论】:
-
在购物车视图中需要使用比较运算符来设置isExpanded。像这样: const isExpanded = this.props.expandedViewId === product.id;
-
啊,是的,你是对的。我更新了它,但应用程序状态更改仍未进入具有新值的子组件。有什么想法吗??
-
商店是否更新了正确的 ID?
标签: reactjs react-native