我正在尝试在 React Native 的自定义抽屉组件中显示按钮列表。 按钮成功加载和呈现,但立即变为"未定义",因此无法单击。 我得到的具体错误是"未定义不是一个对象(评估'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;
};
您在代码中缺少返回调用,因此您的 case 语句失败,并且state.data
在CHANGE_CURRENT_DATA
类型上变得过度。更新您的减速器以在每个案例结束时返回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;
};