简体   繁体   中英

React Native passing of props

Having a really hard time with figuring out why I dont have access to a variable I should have access to.

I have a constructor

 constructor(props) {
      super(props);
      this.state = {
         endpoint:props.url
      };
      console.log(props.url);// Prints url as intended
      console.log(this.state.endpoint);// Also prints as intended

}

Now you would think this would just carry over, to the componentDidMount, but it doesnt?? I thought a constructor was supposed to initiate something with state?

 componentDidMount(){
    fetch(this.state.endpoint).then(etc....)
    // this fails.  If I do console.log(this.state.endpoint) I get undefined.
 }

How do I get the endpoint to work in the fetch function??

I don't really see any reason why your code shouldn't work, but try this...

class MyComponent extends React.Component {
  constructor(props){
    super(props)
  }

  componentDidMount(){
    fetch(this.props.url)
      .then( response => console.log(response) )
  }

}

State should only be set on mounted components, or those components that are inserted into the dom. If you are not using state in your view, there is no guarantee on when it will update correctly. Why are you setting it as state? Just create a variable.

edit: or why not just use this.props.url inside of componentdidmount?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM