ComponentDidMount () is not called when a response component is installed

I am trying to retrieve some data from the server and for some odd reason, componentDidMount() not starting as it should. I added a console.log() statement inside componentDidMount() to check if it was firing. I know that the server request works as it should. I used it without reaction and worked as it should.

 class App extends React.Component { constructor(props, context) { super(props, context); this.state = { obj: {} }; }; getAllStarShips () { reachGraphQL('http://localhost:4000/', `{ allStarships(first: 7) { edges { node { id name model costInCredits pilotConnection { edges { node { ...pilotFragment } } } } } } } fragment pilotFragment on Person { name homeworld { name } }`, {}). then((data) => { console.log('getALL:', JSON.stringify(data, null, 2)) this.setState({ obj: data }); }); } componentDidMount() { console.log('Check to see if firing') this.getAllStarShips(); } render() { console.log('state:',JSON.stringify(this.state.obj, null, 2)); return ( <div> <h1>React-Reach!</h1> <p>{this.state.obj.allStarships.edges[1].node.name}</p> </div> ); } } render( <App></App>, document.getElementById('app') ); 
+7
source share
2 answers

The problem is that the rendering method fails because the next line generates an error

 <p>{this.state.obj.allStarships.edges[1].node.name}</p> 

Correct this so that you do not use this.state.obj.allStarships.edges [1] .node.name directly if you cannot guarantee that each recipient is defined.

+10
source

Check component key

This can also happen if your component does not have a key. In React, a key property is used to determine if a change is simply new properties for a component or whether the change is a new component.

React unmounts the old component and connects the new one only if the key is changed. If you see cases when componentDidMount () is not called, make sure your component has a unique key.

With the key installed, React will interpret them as various components and perform dismantling and installation.

Keyless example:

 <SomeComponent prop1={foo} /> 

Key example

 const key = foo.getUniqueId() <SomeComponent key={key} prop1={foo} /> 
0
source

Source: https://habr.com/ru/post/1244742/


All Articles