0

我正在使用堆栈导航器在本机反应中开发一个多页应用程序。在导航到不同的页面时,我可能会/可能不会传递数据,但在某些情况下,比如“聊天”,我确实会传递在中定义的userB数据,因此为了将my更改为displayName,我创建了一个它的自定义组件并作为道具传递给. 下面是代码:ChatScreenStackNavigatorHeaderChatScreenuserBheaderTitleStack.Screen

<Stack.Navigator>
      <Stack.Screen
        name="Home"
        component={HomeScreen}
        options={{headerTitle: HomeHeader}}
      />
      <Stack.Screen
        name="Chat"
        component={ChatScreen}
        options={{headerTitle: (props) => <ChatHeader {...props} />}} // PROBLEM IS HERE...
      />
      <Stack.Screen
        name="Contacts"
        component={ContactScreen}
        options={{title: 'Select Contact'}}
      />
    </Stack.Navigator>

现在,在其他组件中,我将一些数据传递给Chat屏幕:

const ContactItem = ({item}) => {
  const navigator = useNavigation();
  const {phone, name, profile} = item;
  const [userB, setUserB] = useState(null);

  return (
    <TouchableOpacity
      onPress={() => {
        const formattedPhone = reformat(phone);
        getUserDetails(formattedPhone, setUserB);
        if (userB) {
          console.log(userB);
          navigator.navigate('Chat', {
            user: userB,
          });
        } else {
          ToastMessage(`User with phone number ${formattedPhone} does not exist`);
        }
      }}>
    </TouchableOpacity>
  );
};

现在,在导航到Chat我将userB数据传递到Chat屏幕时,我在ChatHeader组件中获得了以下详细信息:

const ChatHeader = () => {
  const navigator = useNavigation();
  const {params} = useRoute();
  const {user} = params;
  console.log(user);

  return (
    <View style={styles.container}>
      <TouchableOpacity>
        <Image
          source={require('../../../assets/images/user-icon.png')}
          style={styles.image}
        />
      </TouchableOpacity>

      <View style={styles.headerTextContainer}>
        <Text style={styles.headerText}>{user.name}</Text>
      </View>
    </View>
  );
};

错误:

Warning: Cannot update a component (`NativeStackNavigator`) while rendering a different component (`ChatScreen`). To locate the bad setState() call inside `ChatScreen`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render  in ChatScreen (at SceneView.tsx:126).

Error: Couldn't find a route object. Is your component inside a screen in a navigator?  This error is located at:in ChatHeader (at navigation/index.js:47)

当我传入时propsStack.Screen options={{headerTitle: (props) => <ChatHeader {...props} />}}这样可以确保我应该能够继承ChatHeader传递给Chat屏幕组件的数据,对吗?但事实并非如此...

有人能帮我吗?

谢谢!

4

1 回答 1

0

React Navigation 文档

为了在标题中使用 params,我们需要将屏幕的 options 属性设为返回配置对象的函数。

所以你必须改变

options={{headerTitle: (props) => <ChatHeader {...props} />}}

options={(props) => ({headerTitle: <ChatHeader {...props} />})}

于 2022-01-04T07:14:31.447 回答