2017-04-11 54 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