Re-render same component on url change in react

半城伤御伤魂 提交于 2021-02-04 18:48:12

问题


I have a route which takes an id and renders the same component for every id, for example : <Route path='/:code' component={Card}/>

Now the in the Link tag I pass in an id to the component.Now the Card component fetches additional detail based on the id passed. But the problem is it renders only for one id and is not updating if I click back and goto the next id. I searched and found out that componentsWillReceiveProps can be used but during recent versions of React it has been deprecated. So how to do this?


回答1:


Putting current location as key on component solves problem.

<Route path='/:code' component={(props) => <Card {...props} key={window.location.pathname}/>}/>



回答2:


I just ran into a similar problem. I think you are conflating updating/rerendering and remounting. This diagram on the react lifecycle methods helped me when I was dealing with it.

If your problem is like mine you have a component like

class Card extend Component {
  componentDidMount() {
    // call fetch function which probably updates your redux store  
  }

  render () {
    return // JSX or child component with {...this.props} used, 
           // some of which are taken from the store through mapStateToProps
  }
}

The first time you hit a url that mounts this component everything works right and then, when you visit another route that uses the same component, nothing changes. That's because the component isn't being remounted, it's just being updated because some props changed, at least this.props.match.params is changing.

But componentDidMount() is not called when the component updates (see link above). So you will not fetch the new data and update your redux store. You should add a componentDidUpdate() function. That way you can call your fetching functions again when the props change, not just when the component is originally mounted.

componentDidUpdate(prevProps) {
  if (this.match.params.id !== prevProps.match.params.id) {
    // call the fetch function again
  }
}

Check the react documentation out for more details.




回答3:


In React Router v4 Adding a Switch tag after Router fixes the problem




回答4:


I actually figured out another way to do this.

We'll start with your example code: <Route path='/:code' component={Card}/>

What you want to do is have <Card> be a wrapper component, functional preferrably (it won't actually need any state I don't think) and render the component that you want to have rendered by passing down your props with {...props}, so that it gets the Router properties, but importantly give it a key prop that will force it to re-render from scratch

So for example, I have something that looks like this:

<Route exact={false} path="/:customerid/:courierid/:serviceid" component={Prices} />

And I wanted my component to rerender when the URL changes, but ONLY when customerid or serviceid change. So I made Prices into a functional component like this:

function Prices (props) {
    const matchParams = props.match.params;
    const k = `${matchParams.customerid}-${matchParams.serviceid}`;
    console.log('render key (functional):');
    console.log(k);
    return (
        <RealPrices {...props} key={k} />
    )
}

Notice that my key only takes customerid and serviceid into account - it will rerender when those two change, but it won't re-render when courierid changes (just add that into the key if you want it to). And my RealPrices component gets the benefit of still having all the route props passed down, like history, location, match etc.




回答5:


Do something like the following:

static getDerivedStateFromProps(nextProps, prevState) {
  if(nextProps.match.params.id !== prevState.match.params.id) {
    // Here
  }
}


来源:https://stackoverflow.com/questions/52252353/re-render-same-component-on-url-change-in-react

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