【问题标题】:react-router-dom <Link/> is clearing the {history,match,location} props when clicked in ssr applicationreact-router-dom <Link/> 在 ssr 应用程序中单击时正在清除 {history,match,location} 道具
【发布时间】:2020-07-11 13:41:57
【问题描述】:

我无法在服务器端渲染中实现 Link 组件。

<Link to={`/edit/${id}`}>
  <h3>{description}</h3>
</Link>

/edit页面,我有这行代码来测试通过的props:

<h1>{props.match.params.id}</h1>

这会引发错误,因为 ma​​tch 属性未通过。

如果我使用&lt;a&gt;&lt;/a&gt; 而不是&lt;Link/&gt; 包裹/edit 页面与withRouter 我得到了这些道具但是这次我与商店断开连接。

由于&lt;Link/&gt; 在 react-router 内部导航,因此当我单击 &lt;Link/&gt; 时,传递给组件的道具似乎被清除了。我不知道如何解决这个问题。

我将historyApiFallback:true 添加到 webpack.config devServer 对象,但它没有解决问题。

here is the repo

【问题讨论】:

    标签: javascript node.js reactjs server-side react-router-dom


    【解决方案1】:

    您的确切错误是使用 href 属性作为 react-router Link 组件。你应该使用to,如下所示:

    <Link to={`/edit/${id}`}>
      <h3>{description}</h3>
    </Link>
    

    解决这个问题后,你会直接陷入另一个问题。您将在EditExpensePage 页面中获得它:

    const mapStateToProps = (state, props) => {
      return {
        expense: state.expenses.find(
          expense => expense.id === props.match.params.id // here, you will get error the params of undefined
        )
      };
    };
    

    你会得到params of undefined 错误,因为你使用react-redux connect 包装withRouter,实际上你应该用withRouter 包装react-redux connect

    export default withRouter(connect(mapStateToProps)(EditExpensePage));
    

    移动 HOC 后,包裹 match 键的 props 不会被定义。

    【讨论】:

    • 放置href是我的愚蠢。由于 不起作用,我尝试使用路由器继续前进。我以您的方式实现了 withRouter 并且它正在工作。问题是当我用 包装我的组件时,那些参数已经应该被注入了,对吧。
    • @Yilmaz,我有点困惑,我的回答对吗?
    • 你说对了一部分。我会给你投票。但我主要担心 在 ssr 中不起作用,我想知道原因
    • @Yilmaz,为什么你猜它在 SSR 中不起作用?你的证据是什么?你想让&lt;Link&gt;做什么?
    • 非常感谢您的帮助。我想了解我写的所有东西,这样我就可以在学习的同时构建自己的样板。这需要更长的时间,但会让我成为一个更好的开发者。
    猜你喜欢
    • 2019-10-20
    • 2021-01-28
    • 2015-07-18
    • 2018-03-29
    • 2018-04-27
    • 2020-08-29
    • 2021-07-31
    • 2019-01-24
    • 2020-09-27
    相关资源
    最近更新 更多