【发布时间】: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