reactjs
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);
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: http://stackoverflow.com/a/42593250/5185595
Related Links
UIScrollView Canvas Equivalent?
ReactJS - props or propTypes?
React Router V4 structure
Should a view be ordering data?
Unable to load React class component inside other class component
How to get history on react-router v4?
Redux react immutable setIn element changes whole list
react: fade-in/slide-in animation when render component
ReactJS component vendors
css-loader, sass-loader not working webpack 2
The best way to organize your site ready for both PC and SP in reactjs, responsive or 2 sources?
Check data has already been fetched for react-redux in action, reducer or component?
<element>.innerText in component method code does not work properly in enzyme testing. Testing react component with Jest+Enzyme(mount())
React Webpack in Production Error #105
Is there a neater way to connect an input field to a state property in React than onChange?
Safest way to pass access token from webview to react native application?