【问题标题】:React Router Dom with parameter not working properly?带有参数的 React Router Dom 无法正常工作?
【发布时间】:2017-08-13 07:44:07
【问题描述】:

这是我的路由配置代码:

<Switch>
   <Route exact path='/(home)?' component={TodoListHomePage} />
   <Route exact path='/profile/:userId' component={TodoListProfilePage} /> 
   <Route  path='/login' component={SignUpAndLogin} /> 
</Switch>

一切正常,但带有参数的路径很奇怪,第一次点击它工作正常,路径例如

http://localhost:4000/Profile/597c1f43a87ca40d38f79a68

在第 2 次单击时,它会连接 Profile,如下所示:

http://localhost:4000/Profile/Profile/597c1f43a87ca40d38f79a68

然后在例如

http://localhost:4000//Profile/Profile/Profile/Profile/597c1f43a87ca40d38f79a68

这是我点击个人资料链接时调用的函数:

handleProfileClick = (e, {name}) => {
      this.setState({ activeItem: name }); 
      this.props.history.push(name.concat('/'.concat(this.props.viewer._id.toString())));
}

【问题讨论】:

  • 您正在使用相对路径。只需在连接前添加/profile

标签: javascript react-router react-router-dom


【解决方案1】:

您正在使用相对路径。只需在连接前添加/

handleProfileClick = (e, {name}) => {
      this.setState({ activeItem: name }); 
      this.props.history.push("/profile/" + this.props.viewer._id.toString());
}

【讨论】:

  • 感谢它现在可以工作,但是当我重新加载它时,加载资源失败:服务器响应状态为 404(未找到)。可能是什么原因?
  • 嗯...我清除了您的 concat 操作.. 用更新的代码试试?
  • 是的,它现在正在工作,但是当我尝试重新加载时又发生了另一个错误,无法加载资源:服务器响应状态为 404(未找到),但是当我单击它时,它工作得很好,只是在配置文件路由(有问题)上它在重新加载时失败,但在其他路由上它很好。
  • 你的代码在 github 上吗?不确定问题可能是什么,如果它是 404,这意味着该路由尚未定义.. 重新加载时它显示什么 url?也许打开一个新问题并在该问题中链接您的 TodoListProfilePage 组件代码?
  • 我已经搜索过了,认为它是一个 webpack 包,但我不确定,这是我的问题链接:stackoverflow.com/questions/45657732/… 非常感谢
猜你喜欢
  • 2021-02-25
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 2020-05-22
  • 2019-12-18
  • 1970-01-01
  • 2016-05-15
  • 2019-11-25
相关资源
最近更新 更多