【发布时间】:2021-12-31 20:54:04
【问题描述】:
我正在使用堆栈导航器在 react native 中开发一个多页面应用程序。在导航到不同的页面时,我可能/可能不会传递数据,但在某些情况下,例如“聊天”,我确实将 userB 数据传递给在 StackNavigator 中定义的 ChatScreen,因此为了更改 @我的 ChatScreen 到 userB 的 displayName 中的 987654324@,我为它创建了一个自定义的 headerTitle 组件,并作为 Stack.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)
当我在Stack.Screen options={{headerTitle: (props) => <ChatHeader {...props} />}} 中传递props 时,这样可以确保我应该能够继承ChatHeader 中传递给Chat 屏幕组件的数据,对吗?但事实并非如此……
有人可以帮我吗?
谢谢!
【问题讨论】:
标签: javascript react-native react-navigation react-navigation-stack react-navigation-v6