【发布时间】:2018-12-28 15:40:00
【问题描述】:
是否知道如何在 react-native 中从父级向子组件发送道具。我在 react-native 中听说过。但不知道在 react-native 中。 我想要的是当用户按下实际上包含在可触摸不透明度的 onpress 事件中的 AddToCart 按钮时,应该将道具发送到另一个页面。Somone 告诉我有关使用 redux 的信息,但我认为这也可能发生在 react-native 中。
底线:按下时有一个按钮,道具应该被发送到另一个页面。
商品详情页面
应该从哪里发送道具。
cart() {
let product_id = this.props.navigation.state.params.id;
AsyncStorage.getItem('cart_id')
.then((_id) => {
API.post_data(_id, product_id)
.then((data) => {
if (data) {
// this.props.navigation.navigate('Cart', {id: data.cart.id})
// was using this method.But when I directly open
// cart page it gives me an error undefined is not
// an object..blah blah
}
})
})
}
<TouchableOpacity onPress={()=> { this.cart() }} >
<Text>AddToCart<Text>
</TouchableOpacity>
购物车页面
应该在哪里接收道具。
componentDidMount() {
let cart_id = this.props.navigation.state.params.id;
// above method is just total waste.
API.getCartItem(cart_id)
.then((response) => {
if (response) {
this.setState({
data: response
});
} else {
alert('no data')
}
})
}
【问题讨论】:
-
an error undefined is not an object..blah blah你得到的确切错误是什么? -
@Tholle TypeError: undefined is not an object..(评估 this.props.navigation.state.params.id)
-
您可以通过“this.props.navigation.navigate('Cart', {id: data.cart.id})”发送数据并接收检查 if(this.props.navigation. state.params.id){ cart_id = this.props.navigation.state.params.id }
-
我成功获取了数据。但是如果我直接打开购物车页面而不点击 addToCart 按钮..它给我一个错误 undefined is not an object.(评估 this.props.navigation.state.params. id)
-
创建一个正在更新并传递给子组件的本地状态。因此,当您按下按钮时,您会更新父组件中的状态,然后将更新后的状态传递给子组件。
标签: javascript reactjs react-native