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

React中如何将catch块错误作为props传复用组件 路由传参失效如何解决

问题原因

你的写法不生效的核心原因是:在异步请求的catch回调中直接书写JSX标签不会被React识别为需要渲染的内容,只有组件返回值、状态驱动的渲染逻辑中的JSX才会被实际挂载到页面上。

解决方案

方案1:同页面内展示错误组件(无需跳转)

通过React状态管理错误信息,捕获到错误时更新状态,驱动组件渲染:

import { useState } from 'react'
import ErrorComponent from './ErrorComponent'

function YourFunctionalComponent() {
  const [errorCode, setErrorCode] = useState(null)

  const fetchData = () => {
    instance.get(url)
      .then(res => { /* 正常业务逻辑 */ })
      .catch((error)=>{
        if(error.response){
          const code = error.response.status
          setErrorCode(code)
          if(code === 404) console.log("Page Not Found")
          if(code === 400) console.log("Bad Request")
        }
      })
  }

  // 渲染逻辑:存在错误码时优先渲染错误组件
  if(errorCode) {
    return <ErrorComponent err={errorCode}/>
  }

  return (
    {/* 正常页面内容 */}
  )
}

方案2:跳转到独立错误页面(路由传参)

如果你需要跳转到全局错误页展示,可通过路由状态传递错误码:

React Router v5 写法

import { useHistory } from 'react-router-dom'

function YourFunctionalComponent() {
  const history = useHistory()

  const fetchData = () => {
    instance.get(url)
      .catch((error)=>{
        if(error.response){
          // 跳转时携带状态参数
          history.push('/error', { errCode: error.response.status })
        }
      })
  }
}

// 错误页组件取值逻辑
import { useLocation } from 'react-router-dom'
function ErrorComponent() {
  const location = useLocation()
  const errCode = location.state?.errCode
  // 可根据errCode不同值渲染对应错误提示
}

React Router v6 写法

import { useNavigate } from 'react-router-dom'

function YourFunctionalComponent() {
  const navigate = useNavigate()

  const fetchData = () => {
    instance.get(url)
      .catch((error)=>{
        if(error.response){
          navigate('/error', { state: { errCode: error.response.status } })
        }
      })
  }
}

Redirect 传参写法

如果用Redirect组件实现跳转,传参方式如下:

// 捕获错误后更新状态控制Redirect渲染
const [redirectToError, setRedirectToError] = useState(null)

// 渲染逻辑
if(redirectToError) {
  return <Redirect to={{
    pathname: '/error',
    state: { errCode: redirectToError }
  }} />
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:51:04