簡體   English   中英

找不到路線 object。 您的組件是否在導航器的屏幕內? 反應原生

[英]Couldn't find a route object. Is your component inside a screen in a navigator? React Native

我正在使用堆棧導航器在本機反應中開發一個多頁應用程序。 在導航到不同頁面時,我可能/可能不會傳遞數據,但在某些情況下,例如“聊天”,我確實將userB數據傳遞給在ChatScreen中定義的StackNavigator ,因此為了將我的HeaderChatScreen更改為userB ' s displayName,我為它創建了一個自定義headerTitle組件,並在Stack.Screen中作為 prop 傳遞。 下面是代碼:

<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 Screen,我在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)

當我在Stack.Screen options={{headerTitle: (props) => <ChatHeader {...props} />}}中傳遞props時,這樣可以確保我應該能夠繼承ChatHeader中的數據,即傳遞給Chat屏幕組件對嗎? 但事實並非如此...

有人能幫我嗎?

謝謝!

React Navigation 文檔

為了在標題中使用參數,我們需要為屏幕創建一個 function 選項,它返回一個配置 object。

所以你必須改變

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM