如何使用@remix-run/node的redirect实现Remix根路径到/welcome的跳转?
Remix 根路由跳转至/welcome的正确实现方式
问题场景
项目目录结构:
routes/ ├── index.tsx └── welcome/ └── index.tsx
尝试直接在根组件返回redirect报错:
import { redirect } from '@remix-run/node' export default () => redirect('/welcome')
错误信息:Error: Objects are not valid as a React child (found: [object Response]).
尝试throw redirect无效,使用action函数也未触发跳转:
import { redirect } from '@remix-run/node' export function action() { return redirect('/welcome') } export default () => null
正确解决方案
在根路由的loader函数中返回redirect,因为loader会在GET请求加载路由时执行,适合处理这种初始跳转需求:
import { redirect } from '@remix-run/node' export async function loader() { return redirect('/welcome') } // 组件可返回null,跳转后不会渲染该组件 export default () => null
原因说明
- 组件返回值必须是React元素,
redirect()返回的是Response对象,无法作为React子元素,直接返回会触发报错。 action函数默认仅响应POST/PUT/DELETE等非GET请求,直接访问根路径属于GET请求,不会触发action逻辑。- loader函数是Remix处理GET请求数据逻辑的入口,在路由渲染前执行,返回redirect会触发服务器端跳转,完全匹配需求。
内容的提问来源于stack exchange,提问作者James Gentes
相关产品推荐
相关产品推荐

