react-router-dom <Link/> 在 ssr 应用程序中单击时正在清除 {history,match,location} props

IT技术 javascript node.js reactjs server-side react-router-dom
2021-05-28 02:14:00

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

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

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

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

这会引发错误,因为未通过matchprops。

如果我使用withRouter<a></a>而不是<Link/>包装/edit页面,我会得到这些props,但是这次我与商店断开了连接。

由于<Link/>在 react-router 内部导航看起来当我点击时传递给组件的props会被清除<Link/>我不知道如何解决这个问题。

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

这是回购

1个回答

您的确切错误是将hrefprop 用于 react-routerLink组件。您应该使用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错误,因为你withRouter使用 react-redux包装了connect,事实上,你应该connect用 a包装 react-redux withRouter

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

移动 HOC 包裹matchpropskey 后不会是 undefined。