我正在使用 Expo Router 开发 React Native 应用程序。我尝试在屏幕之间导航并通过 URL 查询参数传递
bar_id
、table_id
和 user_id
等参数,但它们未正确传递。当在目标屏幕上接收到参数 table_id
和 user_id
时,它们是未定义的,即使我确信我正在传递它们。
这是我导航到下一个屏幕的方法:
router.push({
pathname: '/client/scan/InviteClientsScreen',
query: { bar_id, table_id, user_id }
});
However, when I try to access the parameters in the target screen using useLocalSearchParams(), I receive undefined for table_id and user_id:
const { bar_id, table_id, user_id } = useLocalSearchParams();
console.log({ bar_id, table_id, user_id });
I’ve also logged the parameters before navigation and confirmed that they are being set correctly, but for some reason, they're coming through as undefined when received.
I've tried the following solutions, but they didn’t work:
1. Using params instead of query for navigation.
2. Adding fallback values like { table_id: 'default' } when parameters are undefined.
3. Ensuring that the parameters are not being overwritten before navigation.
Why am I receiving undefined for table_id and user_id?
Is there something wrong with how I'm passing parameters, or is this an issue with how expo-router handles URL query parameters?
Any suggestions on how to troubleshoot this or best practices for passing parameters in Expo Router?
I've logged the parameters before navigation, and they are set correctly.
The only parameter that seems to work is bar_id. Is this an issue with useLocalSearchParams()?
Thanks for any help!
我不知道是否应该这样做,但我就是这样做的。
传递参数的屏幕:
const handleEditPost = (post) => {
router.push({
pathname: `/(editpost)/${post.post_uid}`,
params: { postData: JSON.stringify(post) },
});
};
参数传递到的屏幕
const { editid, postData } = useLocalSearchParams();
^here {post.post_uid} is being set to editId, and { postData: JSON.stringify(post) }, to postData
const [form, setForm] = useState({
postUid: editid, // Use the post ID from params
useEffect(() => {
// Parse the post data from navigation parameters
if (postData) {
try {
const post = JSON.parse(postData);
console.log('Received post data:', post);
此外,参数传递到的屏幕名为 [editId].js,我不知道这是否对传递参数有帮助,但我认为也许值得一提。