4
votes

I'm using React Native 0.43. I've two components, named ParentComponent and ChildComponent. I want to pass some props from parent to child component. I'm using following code (abridged version) in parent component:

export default class ParentComponent extends Component {

  constructor(props) {
    super(props);

    this.state = {
      latitude: 34.7821,
    };
  }

  render() {
    return (
      <View>
        <ChildComponent latitude={this.state.latitude} />
      </View>
    );
  }

}

My child component is as following:

export default class ChildComponent extends Component {

  constructor(props) {
    super(props);

    this.state = {
      latitude: props.latitude,
    };
  }

  componentWillMount() {
    console.log('Before Mount: ' + this.state.latitude)
  }

  render() {
    return (
        <Text>{'Mounted: ' + console.log(this.state.latitude)}</Text>
    );
  }
}

Now, my console shows following result:

2:14:12 AM: Before Mount: null

2:14:12 AM: Mounted: null

2:14:12 AM: Mounted: 34.7821

Now componentWillMount() in my original code has an API call to a web service which depends on the value of this.state.latitude which clearly is not been passed, at least on the first render. On second render, when this.state.latitude value become available, only the render() function executes, but i need this value in my componentWillMount() function.

What I'm doing wrong here?

3
you can handle it in ComponentDidMountRicha Garg

3 Answers

10
votes

I was not able to receive props value in componentWillMount because this method only executes once, just before initial rendering. Since the props were not being passed from parent to child component on the first rendering, I solve the issue by using componentWillReceiveProps method in my child component. It receives the props on subsequent rendering and updates the original state in my child component. Which makes me able to access my state value. The code I use to solve is following:

  componentWillReceiveProps(nextProps) {
      // update original states
      this.setState({
        latitude: nextProps.latitude,
      });
  }
4
votes

You have to call with "this" term your props.

  constructor(props) {
    super(props);

    this.state = {
      latitude: this.props.latitude,
    };
  }

  componentWillMount() {
    console.log('Before Mount: ' + this.state.latitude)
  }
0
votes

you get props inside

componentWillReceiveProps(nextProps) { // process your work }