首页 > 解决方案 > 返回时 react-native Redux 更新状态

问题描述

我的对象

const initialState = {
1: {
    id: 1,
   price: 280
},
2: {
    id: 2,
    price: 200
}

}

行动

我想为用户点击的项目拿走 100 美元。当我单击第一个项目时,控制台日志工作正常,它给了我 180。但是我怎么能在我的返回函数中做到这一点。我尝试了很多次,但没有更新。

switch (action.type) {
  case 'BUY_ITEM':
    const getId = state[action.index]['price']
    console.log(getId - 100)
    //this console.log works fine
        return {

        }
   }
   return state
}


 <FlatList
 style={{ flex: 1 }}
 data={Object.values(this.props.data)}
 keyExtractor={(item, index) => index.toString()
 }
   renderItem={({ item }) => {
     return (
        <Card style={styles.itemcontainer}>
             <Text style={[styles.text, { fontSize: 20,}]}>${item.price}</Text>
           <Button style={styles.buyItem} bordered onPress={() => this.props.boughtItem(item.id)}>
        <Text style={{ fontSize: 17, paddingHorizontal: 25, color: '#333945', textAlign: 'center' }}>
         <FontAwesome name="cart-plus" style={styles.buyIcon} />
                                {'  '}Add to cart
                                </Text>
                        </Button>
                    </Card >
                )
            }}>
        </FlatList>

标签: react-native

解决方案


不要直接改state。检查下面的代码,

switch (action.type) {
  case "BUY_ITEM":
    return {
      ...state,
      [action.index]: {
        ...state[action.index],
        price: state[action.index]["price"] - 100,
      },
    };
}

希望这对您有所帮助。随意怀疑。


推荐阅读