我想动态更改新组件屏幕的标题标题,但出现以下错误:
TypeError: TypeError: undefined is not an object (evaluating 'navigationData.navigation.getParam')
* screens\CategoryMealsScreen.js:26:42 in navigationOptions
* screens\CategoryMealsScreen.js:10:40 in CategoryMealsScreen
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:9473:27 in renderWithHooks
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:11994:6 in mountIndeterminateComponent
我的代码:
import React from "react";
import { Text, View, StyleSheet, Button } from "react-native";
import { CATEGORIES } from "../data/dummydata";
import Colors from "../constans/Colors";
let titleHeader = "";
const CategoryMealsScreen = props => {
const categoryId = props.navigation.getParam("categoryId");
const selectedCategory = CATEGORIES.find(cat => cat.id === categoryId);
CategoryMealsScreen.navigationOptions(selectedCategory.title);
// console.log(Object.keys(props.navigation));
titleHeader = selectedCategory.title;
return (
<View style={styles.screen}>
<Text>{selectedCategory.title}</Text>
<Button
title="Meals Details"
onPress={() => props.navigation.navigate("MealsDetail")}
/>
</View>
);
};
CategoryMealsScreen.navigationOptions = navigationData => {
const catId = navigationData.navigation.getParam("categoryId");
const selectedCategory = CATEGORIES.find(cat => cat.id === catId);
// console.log(catId);
// console.log(navigationData.navigation.getParam("categoryId"));
return {
headerTitle: selectedCategory.title,
headerStyle: {
backgroundColor: Colors.primaryColor
},
headerTintColor: "white"
};
};
const styles = StyleSheet.create({
screen: {
flex: 1,
justifyContent: "center",
alignContent: "center"
}
});
export default CategoryMealsScreen;
我想控制台日志catId,它确实在控制台中显示了输出,但错误仍然存在。
我可以getParam
在组件内部获取数据,但不能在 CategoryMealsScreen.navigationOptions
有些人认为它的问题与圣经配置有关,但它不起作用,或者我做错了事。是的,我不是使用全局变量titleHeader
来更改标题标题,并且它可以工作,但是仍然很麻烦。
由于诸如find之类的异步任务而出现问题CATEGORIES.find(cat.. This will take a time to complete
解决方案:将async / await与您的功能配合使用,以等待任务完成。
We can set title dynamically using navigationOptions directly in stack configuration.
CategoryMeals : {
screen : CategoryMealsScreen,
navigationOptions: ({ navigation }) => ({
title : navigation.getParam('categoryId', 'CategoryMeals')
}),
},
让我知道你是否还有任何问题
您是否正在获取console.log('selectedCategory',selectedCategory); ???
此链接显示旧错误undefind不是对象
console.log('selectedCategory',selectedCategory); 给我看看你的日志
这是您可以参考的示例reactnavigation.org/docs/en/headers.html