创建一堆可以转换 的货币帮助器/实用函数(例如
转换为 EURtoUSD
、USDtoCAD
等)的最佳方法是什么? >XY
货币,还根据 Redux 状态内的汇率计算 Y
(并且会随着时间的推移而变化)?
例如,我想要实现的目标是这样的:
utils/index.js
export const EURtoUSD = value => value * rate.usd;
// A couple of similar functions here
组件/index.js
import { EURtoUSD } from '../utils/index';
function Payment(props) {
return <div>Amount in USD: { EURtoUSD(props.value) }</div>
}
但我不想使用硬编码 rate
,而是使用 Redux 状态中已有的数据。我可以导出我的费率(从 reducer 的初始状态),但这不会让我走得太远,因为一旦应用程序更新费率,它就会失败。
我花了一整天的时间试图找到解决方案,并了解了很多与 Redux 相关的东西,但我就是无法弄清楚这个。听起来像是我想太多了,这很可能是我错过的一些微不足道的事情,但我只是没有想法。任何提示,甚至是正确方向的插入,我们将不胜感激!
最佳答案
好的。所以我面临着类似的情况。我做的第一件事是将商店移动到另一个名为 store.txt 的文件中。现在商店可以导出并在任何地方使用。
store.js
const store = createStore(reducer,middleWare(...));
export default store;
不要忘记在入口点导入相同的商店(例如index.js),然后将其提供给提供者。
ExchangeCalculator.js
import store from '/yourpath/store'
class ExchangeCalculator{
calculateRate(params){
// you can get the current state stored in the redux store. using getState
let currentState= store.getState();
//take whatever information you want from state and calculate
}
}
关于javascript - 基于 Redux 状态返回值的货币实用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48533152/