You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS/Supabase创建运单后Router.push无法获取ID跳转问题求助

解决运单提交后跳转URL缺失ID的问题

你的代码里有两个核心问题导致跳转URL缺失ID:

  1. Supabase返回数据结构处理错误
    你调用insert([{...}])时传入的是数组,所以Supabase返回的data是包含新增记录的数组(即使只插入一条),直接访问data.id会得到undefined,正确应该取数组第一个元素的id,也就是data[0].id。

  2. useState异步更新的特性
    React的setId是异步操作,调用后id2不会立刻更新为新值,此时直接用id2拼接URL,拿到的还是初始的空字符串。

修改后的handleSubmit函数代码

const router = useRouter()
const [id2, setId] = useState('')

const handleSubmit = async (e) => {
    e.preventDefault()

    if (!location_to_city || !location_to_country || !location_from_city || !location_from_country) {
        setFormError('Please fill in all the fields correctly')
        return
    }

    const { data, error } = await supabase
        .from('shipment')
        .insert([{ location_from_address_1, location_from_zipcode, location_from_city, location_from_country, location_to_address_1, location_to_zipcode, location_to_city, location_to_country, customs, excise, dangerous_goods, documents, documents_information, user_id: user.id }])
        .select()

    if (error) {
        console.log(error)
        setFormError('Please fill in all the fields correctly')
        return // 出错后直接返回,避免后续执行无效逻辑
    }

    if (data && data.length > 0) {
        setFormError(null)
        const newShipmentId = data[0].id
        setId(newShipmentId) // 仅用于后续可能的组件内状态使用
        router.push(`/shipments/${newShipmentId}`) // 直接用刚获取的ID拼接跳转URL
    } else {
        setFormError('Failed to create shipment')
    }
}

关键修改点说明

  • 优先处理错误,出错后直接返回,避免执行后续无效逻辑
  • 校验返回的data是否有效,确保能拿到新增记录的ID
  • 跳转时直接使用同步获取到的newShipmentId,不依赖异步更新的state变量
  • 补充了运单创建失败的错误提示逻辑

内容的提问来源于stack exchange,提问作者DutchEnglishman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:50:21