我已经开始在react native中使用redux,并且在mapStateToProps函数中遇到了问题。我想让这个函数对我存储中的所有变量都通用,这样我就不必更新mapStateToProps函数中的每个变量。
当我点击一个按钮更新一个变量时,例如this.props.secondDishAmount,我也必须更新所有其他变量,因为否则这些变量将变得未定义。
有没有办法更改mapStateToProps函数使其通用?
提前感谢!
class Restaurant extends React.Component {
function mapStateToProps(state) {
return {
firstDishAmount: state.firstDishAmount,
secondDishAmount: state.secondDishAmount
}
}
function mapDispatchToProps(dispatch) {
return {
increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
addFirstDishToCart: () => dispatch({ type: 'ADD_FIRST_DISH_TO_CART' }),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Restaurant);
const initialState = {
firstDishAmount: 0,
secondDishAmount: 0,
thirdDishAmount: 0,
totalPrice: 0,
firstDishPrice: 5.9,
secondDishPrice: 12.6,
thirdDishPrice: 11.9,
}
const shoppingBagItems = (state = initialState, action) => {
console.log(state.firstDishAmount, state.secondDishAmount, state.totalPrice)
switch (action.type) {
case 'INCREASE_COUNTER':
return {
firstDishAmount: state.firstDishAmount + 1,
secondDishAmount: state.secondDishAmount,
totalPrice: state.totalPrice,
firstDishPrice: state.firstDishPrice
}
case 'DECREASE_COUNTER':
return {
firstDishAmount: state.firstDishAmount - 1,
secondDishAmount: state.secondDishAmount,
totalPrice: state.totalPrice,
firstDishPrice: state.firstDishPrice
}
case 'ADD_FIRST_DISH_TO_CART':
return {
totalPrice: state.totalPrice + state.firstDishAmount * state.firstDishPrice,
firstDishAmount: 0,
secondDishAmount: state.secondDishAmount,
firstDishPrice: state.firstDishPrice
}
}
return state
}
export default shoppingBagItems;
import { createStore } from 'redux';
import shoppingBagItems from '../reducers/shoppingBagItems';
export default store = createStore(shoppingBagItems)
要改进此代码,需要做以下几件事:
- 首先,您应该改用我们的官方Redux Toolkit包,这是我们推荐的编写Redux逻辑的方法
- 如果你要写减速器";"手工";,在每种情况下,都应该使用JS对象扩展运算符来扩展现有的状态字段:
case 'DECREASE_COUNTER':
return {
...state,
firstDishAmount: state.firstDishAmount - 1,
}
- 然而,通过使用Redux Toolkit,您可以编写"突变";实际转换为安全的不可变更新的代码:
const shoppingBagSlice = createSlice({
name: "shoppingBag",
initialState,
reducers: {
decreaseCounter(state, action) {
// Can safely "mutate" the existing state inside of `createSlice`
state.firstDishAmount--;
}
}
})
// createSlice generates "action creators" automatically
const { decreaseCounter } = shoppingBagSlice.actions;
export default shoppingBagSlice.reducer;
- 如果要将
connect
与React一起使用,则应使用;对象简写";mapDispatch
的形式:
import { decreaseCounter } from "./shoppingBagSlice";
const mapDispatch = { decreaseCounter };
export default connect(mapState, mapDispatch)(MyComponent);
- 但是,我们也建议使用React-Redux挂钩API而不是
connect
我刚刚发布了一个全新的";Redux Essentials";核心文档教程,教初学者";如何使用Redux,正确的方式";,使用我们最新推荐的工具和实践。我鼓励你去看看:
https://redux.js.org/tutorials/essentials/part-1-overview-concepts