Klick
Klick

Reputation: 1653

componentWillReceiveProps not update state in function

Can someone explain to me, why in example bellow "this.state.time" in function "calcTime" is not updated after "componentWillReceiveProps"?

It is a bit strange because this.state.time in "Text" field is updated every time when component receive new props, but in function "calcTime" "this.state.time" always keep value received from "this.props.time".

Thank you.

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View
} from 'react-native';

export default class Time extends Component {
    constructor(props){
        super(props);
        this.state = {
            time:this.props.Time,
            info:''
        };

    }

    calcTime(){

      console.log('in calcTime '+ this.state.time)
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            time:nextProps.Time
        });
        this.calcTime();

    }


    render(){
        return(
            <View>
               <Text>{this.state.time}</Text>
            </View>
        );
    }
}

AppRegistry.registerComponent('Time', () => Time);

Upvotes: 2

Views: 1251

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104379

setState is asynchronous, you can't expect the updated state value just after the setState. To check the updated values use callback method. Write it like this, it will print the updated value:

componentWillReceiveProps(nextProps) {
    this.setState({
           time : nextProps.Time
        }, () => this.calcTime()
    )
}

Reason As per DOC:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

Check this answer: https://stackoverflow.com/a/42593250/5185595

Upvotes: 3

Related Questions