为什么在redux状态更改时props.screenProps变得不确定

时间:2019-09-08 22:01:45

标签: javascript reactjs react-native react-redux react-navigation-drawer

我试图在React Native的自定义抽屉组件中显示按钮列表。按钮成功加载和渲染,但立即变为“未定义”,因此不可单击。当我单击按钮时,我得到的特定错误是“ undefined不是对象(正在评估'props.screenProps.data.menu.items')”。在单击按钮之前,该应用程序可以正常运行,并且可以查看它们。

我尝试使用一些JS仅在按钮未定义的情况下显示按钮,但是按钮并未显示,因为它们未定义。我的数据存储在redux中。

我的自定义抽屉:

const CustomDrawerComponent = (props) => (
    <Provider store={store}>
        <SafeAreaView style={{ flex: 1 }}>
        <View style={{height: 150, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center'}}>
            <Text style={{marginTop: 50}}> Header Image / Logo</Text>
        </View>    
            <ScrollView>
            { //props.screenProps shows my list of buttons correctly, but clicking on them gives
            //the error of "undefined is not an object"
            //after initially rendering, they switch immediately to undefined
            //as proved by:  '''(props.screenProps.data.menu.items == undefined) &&''' 
            //doesn't show any buttons in the drawer
                props.screenProps.data.menu.items.map((_data) => { return( SideButtonClick(_data) ) })  
                }
            </ScrollView>
        </SafeAreaView>
    </Provider>
)
const SideButtonClick = (data) => {
    return(
        <Button title={data.title} key={data.title} 
            onPress = {() => store.dispatch({
            type: "CHANGE_CURRENT_DATA",
            payload: data }) } 
          />
    );
}

编辑:我的减速器

export const reducer = (state = initialState, action) => {
    switch (action.type) {
        case "CHANGE_CURRENT_DATA": {
            state = {
                ...state,
                title: action.payload.title,
                link: action.payload.link,
                icon: action.payload.icon
            };
                console.log(action.payload);
                }
        case "CHANGE_DATA": {
            state = {
                ...state,
                data: action.payload
            };
             //console.log(action.payload);
        }
    }
    return state;
};

1 个答案:

答案 0 :(得分:1)

您在代码中缺少返回调用,因此您的case语句不正确,state.dataCHANGE_CURRENT_DATA类型上变得不知所措。更新您的reducer以在每种情况下返回state

export const reducer = (state = initialState, action) => {
    switch (action.type) {
        case "CHANGE_CURRENT_DATA": {
            state = {
                ...state,
                title: action.payload.title,
                link: action.payload.link,
                icon: action.payload.icon
            };
                console.log(action.payload);
            return state;
                }
        case "CHANGE_DATA": {
            state = {
                ...state,
                data: action.payload
            };
             //console.log(action.payload);
           return state;
        }
    }
    return state;
};