简体   繁体   English

运行操作时 mapStateToProps 中的道具不会更新 - Redux

[英]Props in mapStateToProps does not update when run an action - Redux

to put them in context a bit, i use redux to update a list in a shopping cart, basically what i do is get the list add an item and update the whole list, when i execute an action i have a cartList that is not updating.把它们放在上下文中,我使用 redux 来更新购物车中的列表,基本上我所做的是让列表添加一个项目并更新整个列表,当我执行一个操作时,我有一个没有更新的 cartList .

I have seen many forums and changed many things but still cannot get it to update automatically, when saving with the fast refresh if it is updated我看过很多论坛并改变了很多东西,但仍然无法让它自动更新,如果它更新了快速刷新保存

Here is my component where I list the items in the shopping cart:这是我列出购物车中商品的组件:

class Cart extends React.Component {

  getTotalPrice = () => {
    //TODO: get total price
    return 'TOTAL: '
  }

  render() {
    const { cartList, navigation } = this.props;
    return (
      <View style={styles.wrap}>
        <SafeAreaView>
          <Text style={styles.title}> Carro de Compras</Text>
        </SafeAreaView>
        <ScrollView style={{ flex: 1 }}>
          <FlatList
            scrollEnabled={false}
            data={cartList}
            numColumns={1}
            renderItem={({ item }) => (
              <CartItem
                navigation={navigation}
                product={item}
              />
            )}
          />
        </ScrollView>
        <View style={styles.navBuy}>
          <Text style={styles.price}>{this.getTotalPrice()}</Text>
          <Text style={styles.buttonBuy}>Comprar</Text>
        </View>
      </View>
    );
  }
}

function mapStateToProps(state) {
  return { cartList: state.cartList }
}

export default connect(mapStateToProps)(Cart);

Here I have all my actions:在这里,我有我所有的行动:

export const setUser = payload => ({
    type: 'SET_USER',
    payload
});

export const setDataMayday = payload => ({
    type: 'SET_DATA_MAYDAY',
    payload
});

export const setDataCartList = payload => ({
    type: 'SET_DATA_CART_LIST',
    payload
});

Here I have my reducer, it is only one since I am learning to use redux, I have seen that you can do several reducer and combine them:这里我有我的 reducer,自从我学习使用 redux 以来只有一个,我已经看到你可以做几个 reducer 并将它们组合起来:

const reducer = (state = {}, action) => {

    switch (action.type) {
        case 'SET_USER':
            return { ...state, ...action.payload }
        case 'SET_DATA_CART_LIST':
            return  { ...state, ...action.payload };
        case 'SET_DATA_MAYDAY':
            return  { ...state, form: { ...state.form, ...action.payload } }
        default:
            return state;
    }
}

export default reducer;

this is store:这是商店:

const persistConfig = {
  key: 'root',
  storage,
}

const persistedReducer = persistReducer(persistConfig, reducer)
const store = createStore(persistedReducer)
const persistor = persistStore(store)

export { store, persistor };

this is App.js:这是 App.js:

export default class App extends Component{
  render() {
    return (
      <Provider store={store}>
        <PersistGate  loading={null} persistor={persistor}>
          <AppNavigator />
        </PersistGate>
      </Provider>
    );
  }
}

update cartList:更新购物车列表:

const handleAddCart = (props) => {

  let list = props.cartList;

    list.push(props.product);

    props.setDataCartList({
      cartList: list
    });

    Alert.alert("Se añadio el producto al carro de compras");

    Api.addItemToCart(item)
      .then(resp => {
        //TODO: handle response
      })
      .catch(error => {
        console.log(error);
      });;
  }


}

ButtonAddCart = (props) => {
  return (
    <TouchableHighlight
      onPress={() => handleAddCart(props)}>
      <View style={style.cart}>
        <Icon name="shopping-cart" size={20} color={'#E1591E'} />
        <Text> Agregar al carro!</Text>
      </View>
    </TouchableHighlight>
  );
}

const mapDispatchToProps = { setDataCartList };

function mapStateToProps(state) {
  return { cartList: state.cartList }
}

export default connect(mapStateToProps, mapDispatchToProps)(ButtonAddCart);

You are mutating state, you shouldn't mutate state by directly pushing to the array.你正在改变状态,你不应该通过直接推送到数组来改变状态。 Create a new array and push values to it.创建一个新数组并将值推送给它。

const handleAddCart = (props) => {

  // create  a copy of the list
  const list = [...props.cartList];

    list.push(props.product);

    props.setDataCartList({
      cartList: list
    });

    Alert.alert("Se añadio el producto al carro de compras");

    Api.addItemToCart(item)
      .then(resp => {
        //TODO: handle response
      })
      .catch(error => {
        console.log(error);
      });;
  }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 调度动作时未调用redux connect mapStateToProps - redux connect mapStateToProps not called when action is dispatched 来自mapStateToProps的ReactJS + Redux道具不会在调度操作上刷新 - ReactJS + Redux props from mapStateToProps do not refresh on dispatching action 正在更改Redux状态,但使用mapStateToProps时道具未定义 - Redux state is being changed but props are undefined when using mapStateToProps Redux mapStateToProps:异步更新后调度操作以关闭弹出窗口 - Redux mapStateToProps: dispatch action to close popup after async update mapStateToProps 应该异步更新道具吗? - Should mapStateToProps update props asynchronously? React / Redux:mapStateToProps实际上并没有将状态映射到props - React / Redux: mapStateToProps not actually mapping state to props React Redux不同步mapStateToProps中的道具 - React redux do not sync props in mapStateToProps React redux mapStateToProps 未设置返回到我的道具 - React redux mapStateToProps not set return to my props 调用Redux操作时道具不更新 - Props not being updated when Redux action is called react redux:当使用Connect for mapStateToProps和mapDispatchToProps时仍然为this.props获取空对象 - react redux: still getting empty object for this.props when using Connect for mapStateToProps and mapDispatchToProps
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM