综合技术

Redux + Typescript: The type of the root state

微信扫一扫,分享到朋友圈

Redux + Typescript: The type of the root state
0

You can get the type of the state from the root reducer

// the reducer
const appReducer = combineReducers({
    global: globalStateReducer,
    example: exampleReducer
});

type AppState = ReturnType<typeof appReducer>

However the redux state can be cleared in some scenarios, so it should be undefinable

//See https://stackoverflow.com/a/35641992/301447 for "undefined redux state" 
type RootState = AppState | undefined;


const rootReducer = (state:RootState, action: Action) => {
    if (action.type === DESTROY_REDUX_STATE) {
        state = undefined;
    }
    return appReducer(state, action)
}

And mapStateToProps() of a component will look like this:

function mapStateToProps(rootState: RootState) {
    return {
        example: rootState!.example  //note the exclamation mark as rootState can be undefined 
    };
}

阅读原文...


Avatar

Prioritization in Quality Assurance — How we do it

上一篇

35+ Premium & Free Email Templates (Top Responsive HTML Designs to Download 2019)

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
Redux + Typescript: The type of the root state

长按储存图像,分享给朋友