温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Unable to set header title dynamically in react native
react-native react-navigation react-navigation-stack

其他 - 无法在React Native中动态设置标题标题

发布于 2020-03-29 21:50:42

我想动态更改新组件屏幕的标题标题,但出现以下错误:

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来更改标题标题,并且它可以工作,但是仍然很麻烦。

的GitHub

查看更多

提问者
Ketan Ramteke
被浏览
27
Prakash Karena 2020-01-31 19:55

由于诸如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')
    }),
},