首页 > 解决方案 > 如何在定义了返回流类型的化简器上使用 Object.assign 和文字

问题描述

我正在编写一个将与React.useReducer钩子一起使用的减速器。使用了 Flow,但 reducer 遇到了流错误,因为Object.assign({}, state ...has{}作为与SearchLocationStateType. 我发现的唯一解决方案是列出每个对象文字上的所有属性,这不是正确的方法。

我该如何解决这个问题?

type SearchLocationStateType = {
    textAreaFocused: boolean,
    promptsShown: boolean,
};

export const ACTIONS = Object.freeze({
    FOCUS_SEARCH_TEXT: 'FOCUS-SEARCH-TEXT',
    BLUR_SEARCH_TEXT: 'BLUR-SEARCH-TEXT',
});

type ActionType = {
    type: $Values<typeof ACTIONS>,
};

const reducer = (state: SearchLocationStateType, action: ActionType): SearchLocationStateType => {
    switch (action.type) {
        case ACTIONS.FOCUS_SEARCH_TEXT:
            return Object.assign({}, state, {textAreaFocused: true});
        case ACTIONS.BLUR_SEARCH_TEXT:
            return Object.assign({}, state, {textAreaFocused: false});
        default:
            return state;
    }
};

标签: javascriptreactjsecmascript-6flow-js

解决方案


推荐阅读