gpt4 book ai didi

javascript - 为什么当 redux 状态改变时 props.screenProps 会变成 undefined

转载 作者:行者123 更新时间:2023-12-02 22:59:22 27 4
gpt4 key购买 nike

我正在尝试在 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 }) }
/>
);
}

编辑:我的 reducer

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.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;
};

关于javascript - 为什么当 redux 状态改变时 props.screenProps 会变成 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57846067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com