2017-04-11 129 views
1

有人可以向我解释为什么在函数“calcTime”中的下例中的“this.state.time”在“componentWillReceiveProps”后没有更新?componentWillReceiveProps不更新函数中的状态

这有点奇怪,因为每当组件接收新道具时,“文本”字段中的this.state.time会更新,但在函数“calcTime”中,“this.state.time”始终保持从“this .props.time”。

谢谢。

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); 
+0

([在reactJs初始呼叫空状态值]的可能的复制http://stackoverflow.com/questions/39567602/empty-state-value-for-initial- call-in-reactjs) –

回答

2

的setState是异步,你不能指望仅仅setState后更新的状态值。要检查更新的值,请使用回调方法。写像这样,将打印更新后的值:

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

的理由,每DOC

的setState()不会立即发生变异this.state而是创建一个 挂起状态转变。调用 方法后访问this.state可能会返回现有值。没有 保证同步操作对setState的调用,并且调用可能为 进行批处理以提高性能。

检查这个答案:https://stackoverflow.com/a/42593250/5185595

+0

它解释了很多:)。谢谢。 – Klick