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
相关产品推荐
相关产品推荐

