【问题标题】:useSelector hook returns 'undefined' from initial stateuseSelector 挂钩从初始状态返回“未定义”
【发布时间】:2020-08-03 10:21:33
【问题描述】:

我正在使用 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
}

减速器'..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/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)

您能否指出可能的问题?

【问题讨论】:

    标签: typescript redux react-redux


    【解决方案1】:

    看起来您已经使用 combineReducers 包装了货币减速器,因此为了检索它,您必须选择如下:

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

    【讨论】:

    • 显然,我应该使用 RootState 而不是 CurrencyExchangeState,这很有意义,因为我正在组合减速器。然后它按预期工作。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2018-08-22
    • 2022-11-16
    相关资源
    最近更新 更多