Storybook中react-router-v6插件设置查询参数后无法获取的解决方法
问题描述
在Storybook中使用storybook-addon-react-router-v6插件设置查询参数,尝试通过URLSearchParams获取时失败。已配置的Story参数如下:
export const Example = () => <UserProfile />; Example.story = { parameters: { reactRouter: { routePath: '/users/:userId', routeParams: { userId: '42' }, routeHandle: "Profile", searchParams: { tab: 'activityLog' }, routeState: { fromPage: 'homePage' }, } } };
Storybook日志输出:
Story rendered: {url: "/hoge?params=fuga", path: "/hoge", routeParams: Object, searchParams: Object, routeMatches: Array(1)...}
解决办法
使用React Router官方钩子获取查询参数
不要直接通过URLSearchParams(window.location.search)读取,因为插件是模拟React Router环境,并非修改真实浏览器URL。在组件中使用useSearchParams钩子:import { useSearchParams } from 'react-router-dom'; const UserProfile = () => { const [searchParams] = useSearchParams(); // 获取配置的tab参数 const activeTab = searchParams.get('tab'); return <div>当前标签页:{activeTab}</div>; };验证插件版本兼容性
确保storybook-addon-react-router-v6和react-router-dom的版本匹配,建议升级到最新稳定版,避免因版本差异导致参数传递异常。理解插件参数传递逻辑
插件的searchParams参数是直接注入到React Router的路由上下文,而非拼接在模拟URL上(日志中的/hoge?params=fuga是插件内部的模拟格式),因此通过路由钩子才能正确获取到配置的tab: 'activityLog'参数。
内容的提问来源于stack exchange,提问作者user48423
相关产品推荐
相关产品推荐

