Fai*_*een 7 reactjs react-native
单击箭头时,"购物车项目视图"需要展开该特定视图并折叠当前展开的其他任何视图.该产品的item id将传递给父组件,以更新要扩展(活动)的视图.虽然id正在传递并在reducer中的expandedItem属性上设置,但是这不会更新到子组件(即使它作为子组件的prop传递).在最后重新评估子组件时,expandedViewItem仍为0,这是它的默认值.有谁知道如何让子组件接收更新的expandedItem值?它为什么还是0?
请观看我调试此问题的视频:https: //youtu.be/qEgxqAyWDpY
这是在子组件中评估值的位置:
render () {
const isExpanded = product.id === this.props.expandedViewId;
Run Code Online (Sandbox Code Playgroud)
这是整个子组件类:
export default class CartProductItem extends Component {
constructor(props) {
super(props);
this.state = {showCounter: false};
}
expandCartProductItem(id) {
this.props.onExpandClick(id);
this.setState(this.state);
}
updateDisplay = (nextProps) => {
// Null check is needed here as 0 is a valid value
if (nextProps.activeIndex !== null && nextProps.activeIndex === this.props.index) {
this.setState({
showCounter: !this.state.showCounter
});
} else if (nextProps.activeIndex !== null && nextProps.activeIndex !== this.props.index) {
this.setState({
showCounter: false
});
}
}
componentWillReceiveProps(nextProps) {
console.log('nextProps: ', nextProps)
}
render() {
const serverUrl = getServerAddress();
const {product} = this.props;
const price = product.iogmodPrice ? product.iogmodPrice : product.price;
const isExpanded = product.id === this.props.expandedViewId;
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.expandCartProductItem(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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是父组件函数,它将id传递给action,并在render中传递初始const声明:
expandAndCollapseItems = (id) => {
this.props.dispatch(collapseCartItemViews(id));
}
render() {
const {isLoading, displayDetails, sortCasesAsc, details, items, expandedItem} = this.props.orderInfo;
Run Code Online (Sandbox Code Playgroud)
这是父组件中的子组件,其中extendsItem变量被传递给它:
<FlatList
data={items}
keyExtractor={(item, index) => item.id.toString()}
renderItem={({item}) => <CartProductItem product={item} expandedViewId={expandedItem} onExpandClick={(id) => this.expandAndCollapseItems(id)} />}
/>
Run Code Online (Sandbox Code Playgroud)
最后,这里是reducer函数更新app状态:
case types.SET_EXPANDED_STATE:
const id = action.id;
return {
...state,
expandedItem: id
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
171 次 |
| 最近记录: |