javascript - 在 redux reducer 和 actions 中编写相同的函数行为
问题描述
我想问如何使用redux reducers 和actions 重写相同的函数行为。
我需要为redux实现一个功能
handleSelect = itemValue => {
this.setState(
{
...this.state,
base: itemValue,
result: null,
},
this.calculate,
);
};
我所做的第一步是创建一个 actionTypes.js 和 action.js 文件。actionTypes.js 下面的代码
export const HANDLE_FIRST_SELECT = 'HANDLE_FIRST_SELECT';
和我的 action.js
import * as actionTypes from './actionTypes';
export const handleFirstSelect = itemValue => {
return {
type: actionTypes.HANDLE_FIRST_SELECT,
itemValue: itemValue,
};
};
在下一步中,我创建了一个如下所示的减速器
import React from 'react';
import * as actionTypes from '../actions/actionTypes';
const initialState = {
currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR', 'PLN', 'GBP'],
base: 'EUR',
amount: '',
convertTo: 'PLN',
result: '',
date: '',
};
const exchangeCurriences = (state = initialState, action) => {
switch (action.type) {
case actionTypes.HANDLE_FIRST_SELECT:
return {
...state,
[action.itemValue]: state.base[action.itemValue],
result: null,
};
default:
return state;
}
};
export default exchangeCurriences
接下来我像这样在我的容器文件中创建了 mapStateToProps 和 mapDispatchToProps 函数
const mapStateToProps = state => {
return {
baseCurrency: state.base,
amountPrice: state.amount,
convertToPrice: state.convertTo,
result: state.result,
actualDate: state.date,
};
};
const mapDispatchToProps = dispatch => {
return {
handleFirstSelect: itemValue => dispatch(exchangeCurriencesActions.handleFirstSelect(itemValue)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(HomeContentContainer);
当然,我有带有商店道具的 Provider
export default class App extends React.Component {
render() {
const store = createStore(exchangeCurriences);
return (
<Provider store={store}>
<NavigationContainer>
<StatusBar hidden={true} />
<MainTabNavigator />
</NavigationContainer>
</Provider>
);
}
}
当我将handleFirstSelect(来自mapDispatchToProps)传递到我的组件函数道具时,它不像以前那样工作。有谁知道错在哪里?任何有关解决方案的帮助将不胜感激。
解决方案
这条线看起来很奇怪:
[action.itemValue]: state.base[action.itemValue]
您将 state.base 初始化为“EUR”单个字符串,而不是像上面的 reducer 代码中那样的数组。
从您的原始代码中,您只需将 state.base 设置为 action.itemValue 已在操作 handleFirstSelect 中设置
因此,我希望您的减速器代码如下所示:
const exchangeCurriences = (state = initialState, action) => {
switch (action.type) {
case actionTypes.HANDLE_FIRST_SELECT:
return {
...state,
base: action.itemValue, // correct this line
result: null,
};
default:
return state;
}
};