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

React TypeScript下React Router用render属性做缺省跳转类型报错如何解决

问题根因
  • React Router v5 的Route组件render属性要求回调函数必须返回合法的React.ReactNode类型值,你当前的render回调仅执行了history.push没有返回值,不符合类型定义,因此触发类型报错。
  • 补充逻辑问题:你当前用path="/"匹配兜底路由是错误的,只会匹配根路径,要命中所有未匹配的路由需要改为path="*",且跳转目标应该填写/error而非空串。
修复方案

方案1:调整render回调并补充类型声明

给render的回调参数显式声明RouteComponentProps类型,执行跳转后返回空节点满足类型要求:

import { RouteComponentProps } from 'react-router-dom';

const App: React.FC<RouteComponentProps> = ({ history }) => {
  return (
    <Switch>
      <Route path="/" component={ChartContainer} exact />
      <Route path="/error" component={Error} />
      <Route 
        path="*" 
        render={(props: RouteComponentProps) => {
          history.push('/error');
          return null;
        }} 
      />
    </Switch>
  )
}

方案2(更推荐):使用Redirect组件实现重定向

无需依赖上层history注入,写法更简洁,天然符合类型要求:

import { Redirect } from 'react-router-dom';

const App: React.FC = () => {
  return (
    <Switch>
      <Route path="/" component={ChartContainer} exact />
      <Route path="/error" component={Error} />
      <Route path="*" render={() => <Redirect to="/error" />} />
    </Switch>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:24:00