我正在尝试使用导航来导航并将道具传递到另一个组件,但是由于某些原因,这些道具在目标屏幕中变得不确定。
我有一个带有平面列表的主屏幕,平面列表上的每个项目都将用户移至第二个屏幕,其中包含列表项中的相应数据。
这是主屏幕平面列表和导航功能:
async function showConversation(company: Company) {
const currentUser: User = await StorageHelper.retrieveEntity() as User;
const from = currentUser.uid;
const to = company.uid;
console.log(from); <-- logs correctly
console.log(to); <-- logs correctly
navigation.navigate('Conversation', {to: to, from: from});
}
return (
<FlatList<Company>
data={companies}
renderItem={({item}) => (
<TouchableOpacity onPress={() => showConversation(item)}>
<CompanyCard company={item} />
</TouchableOpacity>
)}
keyExtractor={(item) => item.uid}
showsVerticalScrollIndicator={false}
/>
)
这是我的“对话”屏幕:
interface conversationScreenProps {
navigation: any;
to: string
from: string;
}
const ConversationScreen = ({
navigation,
to,
from,
}: conversationScreenProps) => {
const [messages, setMessages] = useState<Array<IMessage>>([]);
const [chatMessage, setChatMessage] = useState<string>('');
const socket = io('http://127.0.0.1:3000');
console.log(to); <-- logs undefined
console.log(from); <-- logs undefined
}
我看到了与此类似的问题,但我仍然不知道为什么会这样。
答案 0 :(得分:2)
参数在路线道具内部传递,它们不作为单独的道具传递。 您将必须按如下方式访问它
const ConversationScreen = ({
navigation,
route
}: conversationScreenProps) => {
const [messages, setMessages] = useState<Array<IMessage>>([]);
const [chatMessage, setChatMessage] = useState<string>('');
const socket = io('http://127.0.0.1:3000');
console.log(route.params.to); <-- logs undefined
console.log(route.params.from); <-- logs undefined
}
您可以在此处查看参考 https://reactnavigation.org/docs/params/
答案 1 :(得分:0)
您应该这样访问它们。因为您不是直接传递道具而是通过反应导航。
let to = navigation.state.params.to
let from = navigation.state.params.from