Hello. I am trying to display data from different url through one component. Data is output, but when the url is changed, it is taken from the original request. componentDidMount (see code below) only works when the component is first rendered. I ask for your help. It is necessary that the component is rendered every time anew with new data when its dynamic url changes.

 <Route path="/animals/:type/:advertisment" component={AnimalCard} /> componentDidMount() { let animal_type = this.props.params.type; let advertisment = this.props.params.advertisment; $.ajax({ url: "http://localhost:8091/list-animals?animal_type=" + animal_type + "&advertisement_type=" + advertisment, dataType: "json", success: (data) => { //здесь в Redux Store отправляются полученные данные this.props.getServerData(data); console.log("ele" + animal_type, advertisment); } }) } 

1 answer 1

I will duplicate my answer from this question, the problem is similar, try to adapt to your code

Found two solutions.

The first is the added key attribute on the component, the key changes (I take it from the routing) and this forces the reactant to remount the component

 let name = this.props.params.element; ... <ElementDetail name={name} key={name} /> 

Changing the key causes ComponentDidMount () each time.

 @connect( state => ({ element: state.element }), dispatch => ({elementActions: bindActionCreators(elementActions, dispatch)}) ) export default class ElementDetail extends React.Component { componentDidMount() { let { getProperties } = this.props.elementActions; getProperties(this.props.name) } ... 

The second is using componentWillReceiveProps () (thanks to Nick for the tip)

 let name = this.props.params.element; ... <ElementDetail name={name} /> 

And in the component itself

 @connect( state => ({ element: state.element }), dispatch => ({elementActions: bindActionCreators(elementActions, dispatch)}) ) export default class ElementDetail extends React.Component { componentWillReceiveProps(nextProps) { if (nextProps.name !== this.props.name) { let { getProperties } = this.props.elementActions; getProperties(nextProps.name) } } componentDidMount() { let { getProperties } = this.props.elementActions; getProperties(this.props.name) } ... 

but in the second method there is more code and it is duplicated.

If someone gives their explanations and comments, it will be excellent 1 : https://ru.stackoverflow.com/users/237588/nick

  • Thank you for help. Helped the first option. - parser