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

如何将参数从React Router传递到组件?访问/signin触发两次日志问题

问题根因

Route的component属性要求传入组件本身,而你的代码中直接传入了Pages.auth(xxx)的执行结果。App组件渲染时,所有路由配置里的Pages.auth(config.url.text)、Pages.auth("signout")都会同步执行,和路由是否匹配无关,exact属性仅控制路由匹配后哪个组件渲染到页面,无法阻止JSX中直接调用的函数执行,所以会打印两次日志。

修复方案

方案1:使用render属性传递参数

render的回调函数仅在路由匹配时才会执行,修改路由配置即可:

// app.js 对应路由部分修改
<Route
  exact
  path={config.url.pathName}
  render={() => Pages.auth(config.url.text)}
/>
<Route exact path="/signout" render={() => Pages.auth("signout")} />

方案2:调整组件写法,通过props传参

先修改auth组件,把参数改为从props读取:

// page/auth.js
import React from "react";
import { page as Page } from "pages";
import { AuthContainer } from "containers";

function Auth(props) {
  const { type } = props;
  console.log("page auth", type);
  return (
    <>
      <Page title={"login"} />
      <AuthContainer type={type} />
    </>
  );
}

export default Auth;

再修改路由配置,匹配时给组件传参:

// app.js 对应路由部分修改
<Route
  exact
  path={config.url.pathName}
  render={(props) => <Auth {...props} type={config.url.text} />}
/>
<Route exact path="/signout" render={(props) => <Auth {...props} type="signout" />} />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:45:04