预期结果
-
之后
this.props.startGetPrices()
在我的主容器中调用。
-
-
然后应该更新Redux状态,从而更新容器中的状态。
-
调用操作时,API返回数组中的格式化数据,将资产发送到reducer中,但Redux状态不更新。
My store.ts文件:
import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunkMiddleware from 'redux-thunk'
import { getLatest } from './services/api'
export interface IinitialState {
assets: any[];
wallets: any[];
defaultCurrency: string;
}
export interface IPricesRes {
data: IPriceData
}
export interface IPriceData {
base: string;
date: string;
rates: any;
success: boolean;
timestamp: number;
}
const defaultInitialState = {
assets: [],
wallets: [],
defaultCurrency: ''
}
export const actionTypes = {
GET_PRICES: 'GET_PRICES'
}
export const reducer = (state = defaultInitialState, action: any) => {
switch (action.type) {
case actionTypes.GET_PRICES: {
const { payload } = action;
console.log('payload', payload);
return {
assets: payload,
...state
};
}
default:
return state;
}
}
export const actionGetPrices = (rates: any) => ({
type: actionTypes.GET_PRICES,
payload: rates
});
export const startGetPrices = () => (dispatch: any) => getLatest().then((ratesArray) => {
dispatch(actionGetPrices(ratesArray));
});
export function initializeStore(initialState = defaultInitialState) {
return createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(thunkMiddleware))
)
}
import React from 'react'
import { connect } from 'react-redux'
import { startGetPrices, IPricesRes } from '../store'
import { CurrencySelector, Header, Prices, Navigation } from '../components'
interface IProps {
assets: [];
wallets: [];
defaultCurreny: string;
startGetPrices(): IPricesRes;
}
class FiatWallet extends React.PureComponent<IProps> {
componentDidMount() {
console.log('FiatWallet componentDidMount...');
this.props.startGetPrices();
}
public render() {
const { assets } = this.props;
console.log('assets from redux state:', assets);
return (
<section>
<CurrencySelector />
<Header />
<Prices prices={assets} />
<Navigation />
</section>
);
}
}
const mapDispatchToProps = (dispatch: any) => ({
startGetPrices: () => dispatch(startGetPrices())
});
const mapStateToProps = (state: any) => ({
assets: state.assets,
wallets: state.wallets,
defaultCurrency: state.defaultCurrency
});
export const BoardJest = FiatWallet;
export default connect(mapStateToProps, mapDispatchToProps)(FiatWallet);
我的转换器Util
// Takes rates { key : value } pairs and converts into Array of objects.
export const ratesIntoArray = ({ data: { rates } }: any) =>
Object.keys(rates).map(data => new Object({ [data]: rates[data]}));