useSelector挂钩从初始状态返回“未定义”

时间:2020-08-03 01:22:19

标签: typescript redux react-redux

我正在玩React / Redux / TypeScript堆栈,并试图弄清楚它是如何工作的以及应该如何工作。

我有一个简单的测试应用程序,当我尝试从初始状态获取数据时-我收到的所有值均为“未定义”(无论我试图从初始状态获取什么)。

请参见下面的代码:

组件:

import { useSelector, useDispatch } from 'react-redux';
import { CurrencyExchangeState } from '../store/exchange/types';

export const Exchange = () => {

    // tried this before - same result
    // const currentCurrency = useSelector<CurrencyExchangeState,
    //     CurrencyExchangeState["currentCurrency"]>
    //     (state => state.currentCurrency);

    const selectCurrentCurrency = (state: CurrencyExchangeState) => state.currentCurrency
    const currentCurrency = useSelector(selectCurrentCurrency)
    
    console.log(currentCurrency) // undefined
    // <...>

类型界面'../ store / exchange / types.ts':

export interface CurrencyExchangeState {
    sum: number,
    mode: string,
    currentCurrency: string
}

Reducer'..store / exchange / reducers.ts':

import {
  CurrencyExchangeState,
  CurrencyExchangeActionTypes,
  // ...
} from './types'

const initialState: CurrencyExchangeState = {
  sum: 0,
  mode: BUY_MODE,
  currentCurrency: UAH_CURRENCY
}

export function currencyExchangeReducer(
  state = initialState,
  action: CurrencyExchangeActionTypes
): CurrencyExchangeState {
  switch (action.type) {
    case TOGGLE_BUY_SALE:
      return {
        ...state,
        mode: action.payload
      }
    case SWITCH_CURRENCY:
      return {
        ...state,
        currentCurrency: action.payload
      }
    default:
      return state
  }
}

Redux Store索引文件'../ store / index.ts':

import { combineReducers, createStore } from 'redux';
import { currencyExchangeReducer } from './exchange/reducers'

const rootReducer = combineReducers({
    currencyExchangeReducer: currencyExchangeReducer
})

export type RootState = ReturnType<typeof rootReducer>
export const exchangeStore = createStore(rootReducer)

能否请您指出可能是错误的?

1 个答案:

答案 0 :(得分:0)

您似乎已经使用combineReducers包装了货币兑换器,因此要检索它,必须选择以下内容:

const selectCurrentCurrency = (state: CurrencyExchangeState) => state.currencyExchangeReducer.currentCurrency)