您好,登錄后才能下訂單哦!
在TypeScript中使用Redux通常需要做一些額外的工作來確保類型安全和正確性。下面是一些與TypeScript配合使用Redux的常見做法:
// actionTypes.ts
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
// actions.ts
interface IncrementAction {
type: typeof INCREMENT;
}
interface DecrementAction {
type: typeof DECREMENT;
}
export type Action = IncrementAction | DecrementAction;
// state.ts
interface CounterState {
count: number;
}
const initialState: CounterState = {
count: 0,
};
export default initialState;
// reducer.ts
import { Action } from './actions';
import initialState, { CounterState } from './state';
const counterReducer = (state: CounterState = initialState, action: Action): CounterState => {
switch (action.type) {
case INCREMENT:
return { count: state.count + 1 };
case DECREMENT:
return { count: state.count - 1 };
default:
return state;
}
};
export default counterReducer;
createStore
函數(shù)創(chuàng)建store時(shí),可以通過泛型指定store的state類型。// store.ts
import { createStore } from 'redux';
import counterReducer from './reducer';
import { CounterState } from './state';
const store = createStore<CounterState>(counterReducer);
export default store;
通過以上方式,可以在TypeScript中使用Redux,并保證類型安全和正確性。同時(shí),使用Redux Toolkit等工具也可以簡(jiǎn)化Redux的使用,并提供更好的類型支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。