react-native - 组件获取道具未定义
问题描述
我正在尝试使用导航来导航并将道具传递给另一个组件,但由于某种原因,道具在目标屏幕中变得未定义。
我有一个带有平面列表的主屏幕,平面列表上的每个项目都会将用户移动到第二个屏幕,其中包含列表项中的相应数据。
这是主屏幕平面列表和导航功能:
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
}
我看到了与这个类似的问题,但我仍然无法弄清楚为什么会这样。
解决方案
参数在路由道具内部传递,它们不会作为单独的道具传递。您必须像下面这样访问它
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/
推荐阅读
- python - PyCharm 导入 matplotlib.pyplot 显示错误
- symfony - 使用 RMQ 在 Symfony Messenger 中处理来自不同命名空间的消息
- vuejs2 - 如何对 vuejs 中两个或多个监视属性的更改做出一次反应
- bash - 比较第一个以 ; 结尾的字符串 在 2 个 txt 文件中,只获取那些唯一的行
- excel - 一次运行多个工作簿
- oracle - ORA-00923 FROM 关键字未指定
- sql - 使用 PowerShell 将 SSIS 项目部署到 Azure SSIS DB 时出错
- c# - 选择属性包含某个子字符串的元素
- numpy - np.random.standard_normal 和 np.random.randn 有什么区别?
- javascript - 在 React Native 中关闭警报