道具类型失败。我的Redux商店中未定义必需的道具类型

时间:2019-07-31 16:52:49

标签: javascript reactjs typescript redux react-redux

因此,我正在学习react和redux,并且每次加载页面时都会在控制台中收到此错误。我不确定这是什么意思,因为我的商店应该正确连接(据我所知,但显然不是)。

  

警告:道具类型失败:道具open在> Navigation中标记为必需,但其值为undefined

这是组件(简化为我认为的关键部分)

Navigation.propTypes = {
    open: PropTypes.bool.isRequired,
};

const mapStateToProps = (state: any) => ({
    open: state.open,
})

export default connect(mapStateToProps, { shiftContent })(Navigation);

我的动作

export const shiftContent = (open: boolean) => {
    return {
        type: ContentTypes.SHIFT_CONTENT,
        payload: open
    }
}

我的减速器:

const initialState = {
    open: false,
};

export default function(state = initialState, action: IAction) {
    switch(action.type) {
        case ContentTypes.SHIFT_CONTENT:
            console.log("shifting Open = " + action.payload);
            return {
                ...state,
                open: action.payload
            };
        default:
            return state;
    }
}

我的组合减速器:

import ContentReducer from './ContentReducer';

const rootReducer = combineReducers({
    content: ContentReducer
});

以及我要初始化商店的位置

import rootReducer from './Reducers';

const store = createStore(rootReducer);

我尝试为商店设置初始状态,例如:

const initialStore = {
   open: false
}
const store = createStore(rootReducer, initialStore);

但这也给了我一个错误。

2 个答案:

答案 0 :(得分:3)

const mapStateToProps = (state: any) => ({
    open: state.open,
})

在此功能中,state是根状态。即,由rootReducer产生的那个。此状态如下:

{
  content: {
    open: // some boolean
  }
}

要访问它,您需要执行以下操作:

const mapStateToProps = (state: any) => ({
    open: state.content.open,
})

PS,由于您使用的是打字稿,因此您应该能够比any做得更好。至少,您可以这样做:

// in the file with the root reducer:
const rootReducer = combineReducers({
    content: ContentReducer
});
export type RootState = ReturnType<typeof rootReducer>;

// And then use it elsewhere like:
const mapStateToProps = (state: RootState) => ({
    open: state.content.open,
})

答案 1 :(得分:0)

mapStateToProps获取根减速器状态-因此请使用state.content.open而不是state.open。