更新阵列时Redux状态未更新

时间:2019-02-01 19:31:36

标签: javascript reactjs typescript redux

预期结果

  • 在我的主容器中调用this.props.startGetPrices()之后。
  • 命中该API,并将数据返回给reducer。
  • 然后应该更新Redux状态,从而更新Container中的状态。

结果

  • 调用动作,API返回数组中的格式化数据,资产发送到reducer,但是Redux状态不会更新。

enter image description here

enter image description here

enter image description here

我的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: ''
}

// ACTION TYPES
export const actionTypes = {
  GET_PRICES: 'GET_PRICES'
}

// const updateAssets = (state: IinitialState, action: any) => {
//   const { assets } = state;
//   const newArray = new Array(action.payload, ...assets)[0];
//   return newArray;
// }

// REDUCER
export const reducer = (state = defaultInitialState, action: any) => {
  switch (action.type) {
    case actionTypes.GET_PRICES: {
      const { payload } = action;
      console.log('payload', payload);
      // const newAssets = updateAssets(state, action);
      // console.log('newAssets', newAssets);
      return {
        // assets: new Array(payload, ...state.assets)[0],
        assets: payload,
        ...state
      };
    }

    default:
      return state;
  }
}

// ACTIONS CREATORS
export const actionGetPrices = (rates: any) => ({
  type: actionTypes.GET_PRICES,
  payload: rates
});

// ACTIONS
export const startGetPrices = () => (dispatch: any) => getLatest().then((ratesArray) => {
  dispatch(actionGetPrices(ratesArray));
});

// @ts-ignore
export function initializeStore(initialState = defaultInitialState) {
  return createStore(
    reducer,
    initialState,
    composeWithDevTools(applyMiddleware(thunkMiddleware))
  )
}

我的容器文件FiatWallet.tsx

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);

我的转换器实用程序

// 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]}));

1 个答案:

答案 0 :(得分:1)

更改此行

return {
    // assets: new Array(payload, ...state.assets)[0],
    assets: payload,
    ...state
  };

对此

return {
    ...state
    // assets: new Array(payload, ...state.assets)[0],
    assets: payload,    
  };

问题是,你是被分配新建分配FY后做的解构与替换旧的新的值。