我正在使用堆栈导航器在本机反应中开发一个多页应用程序。在导航到不同的页面时,我可能会/可能不会传递数据,但在某些情况下,比如“聊天”,我确实会传递在中定义的userB
数据,因此为了将my更改为displayName,我创建了一个它的自定义组件并作为道具传递给. 下面是代码:ChatScreen
StackNavigator
Header
ChatScreen
userB
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)
当我传入时props
,Stack.Screen options={{headerTitle: (props) => <ChatHeader {...props} />}}
这样可以确保我应该能够继承ChatHeader
传递给Chat
屏幕组件的数据,对吗?但事实并非如此...
有人能帮我吗?
谢谢!