react-router-dom <Link/> is clearing the {history,match,location} props when clicked in ssr application

冷暖自知 提交于 2020-04-15 17:16:04

问题


I could not implement the Link component in server-side rendering.

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

In /edit page, I have this line of code to test the props that passed:

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

this throws an error because match prop is not passed.

If I used <a></a> instead of <Link/> wrapped /edit page with withRouter I get those props however this time I am disconnected from the store.

Since <Link/> navigates inside react-router looks like props that passed to components are cleared up when I click on <Link/>. I could not figure out how to solve the issue.

I added historyApiFallback:true to webpack.config devServer object but it did not solve the issue.

here is the repo


回答1:


Your exact mistake is using href prop for the react-router Link component. you should use to, like below:

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

After fixing this issue, directly you will fall into another issue. you will get it inside EditExpensePage page:

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
    )
  };
};

You will get params of undefined error because you wrap the withRouter by using react-redux connect, in fact, you should wrap react-redux connect by a withRouter:

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

After moving HOC wrapping the match key of props won't be undefined.



来源:https://stackoverflow.com/questions/60943237/react-router-dom-link-is-clearing-the-history-match-location-props-when-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!