Как обновить компонент при изменении данные в AsyncStorage в React Native?
Всем привет! Создаю корзину для магазина и сталкивался с такой проблемой: При нажатий кнопки addToCart компонент CartIcon автоматический не обновляется (( Что сделать ??? (Задача такая чтобы было через AsyncStorage, а не redux)
Main.js
import React, {Component} from 'react'
import { View, Text } from 'react-native'
import Product from './Product'
import CartIcon from './CartIcon'
class Main extends Component{
render(){
return(
<View>
<Text>Main Page</Text>
<Product title="Iphone" price="100000" count="1" />
<Product title="Samsung" price="100000" count="1" />
<Product title="Redmi" price="100000" count="1" />
<CartIcon />
</View>
)
}
}
export default Main
Product.js
import React, {Component} from 'react'
import { View, Text, AsyncStorage, TouchableOpacity } from 'react-native'
class Product extends Component{
constructor(props){
super(props)
this.state = {
cart: null
}
}
addToCart(){
const { price, count } = this.props
const itemcart = {
quantity: count,
price: price
}
AsyncStorage.getItem('cart').then((datacart)=>{
if (datacart !== null) {
// We have data!!
const cart = JSON.parse(datacart)
cart.push(itemcart)
AsyncStorage.setItem('cart',JSON.stringify(cart));
} else{
const cart = []
cart.push(itemcart)
AsyncStorage.setItem('cart',JSON.stringify(cart));
}
alert("Added to Cart")
})
.catch((err)=>{
alert(err)
})
}
render(){
return(
<View>
<Text>{this.props.title}</Text>
<Text>{this.props.price}</Text>
<Text>{this.props.count}</Text>
<TouchableOpacity onPress={() => this.addToCart()}></TouchableOpacity>
</View>
)
}
}
export default Product
CartIcon.js
import React, {Component} from 'react'
import { View, Text, AsyncStorage } from 'react-native'
class CartIcon extends Component{
constructor(props){
super(props)
this.state = {
cart: null
}
}
componentDidMount(){
AsyncStorage.getItem('cart').then((cart)=>{
if (cart !== null) {
// We have data!!
const cartfood = JSON.parse(cart)
this.setState({cart: cartfood})
}
})
.catch((err)=>{
alert(err)
})
}
render(){
const { cart } = this.state
let price = 0
if(cart !== null){
this.state.cart.map((item,i)=>{
price += item.price * item.quantity
})
}
return(
<View>
<Text> Total Sum: {price} </Text>
</View>
)
}
}
export default CartIcon
Ответы (1 шт):
Автор решения: Sergei Kirjanov
→ Ссылка
Можно сделать стейт с версией в общем парент компоненте.
Пробросить функцию инкремента версии в компонент Product.
Пробросить значение версии в CartIcon.
Позавершению setItem делать инкремент версии.
В CartIcon делать getItem по изменению (prop) версии.