React-router urls don't work when refreshing or writing manually

前端 未结 30 2644
时光取名叫无心
时光取名叫无心 2020-11-21 05:07

I\'m using React-router and it works fine while I\'m clicking on link buttons, but when I refresh my webpage it does not load what I want.

For instance, I am in

30条回答
  •  孤街浪徒
    2020-11-21 05:55

    I'm not using server side rendering yet but I hit the same problem as the OP where Link seemed to work fine most of the time but failed when I had a parameter. I'll document my solution here to see if it helps anyone.

    My main jsx contains this:

    
    

    This works fine for the first matching link but when the :id changes in expressions nested on that model's detail page, the url changes in the browser bar but the content of the page did not initially change to reflect the linked model.

    The trouble was that I had used the props.params.id to set the model in componentDidMount. The component is just mounted once so this means that the first model is the one that sticks on the page and the subsequent Links change the props but leave the page looking unchanged.

    Setting the model in the component state in both componentDidMount and in componentWillReceiveProps (where it is based on the next props) solves the problem and the page content changes to reflect the desired model.

提交回复
热议问题