Reactjs componentWillReceiveProps未在函数中更新状态

Reactjs componentWillReceiveProps未在函数中更新状态,reactjs,react-native,Reactjs,React Native,有人能给我解释一下,为什么在示例中,函数“calcTime”中的“this.state.time”在“componentWillReceiveProps”之后没有更新 这有点奇怪,因为每当组件接收到新的道具时,“Text”字段中的this.state.time都会更新,但在函数“calcTime”中,“this.state.time”总是保留从“this.props.time”接收到的值 多谢各位 import React, { Component } from 'react'; import

有人能给我解释一下,为什么在示例中,函数“calcTime”中的“this.state.time”在“componentWillReceiveProps”之后没有更新

这有点奇怪,因为每当组件接收到新的道具时,“Text”字段中的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);
import React,{Component}来自'React';
进口{
评估学,
样式表,
文本,
看法
}从“反应本机”;
导出默认类时间扩展组件{
建造师(道具){
超级(道具);
此.state={
时间:这个。道具。时间,
信息:“”
};
}
计算时间(){
console.log('in calcTime'+this.state.time)
}
组件将接收道具(下一步){
这是我的国家({
时间:下一步
});
这是calcTime();
}
render(){
返回(
{this.state.time}
);
}
}
AppRegistry.registerComponent('Time',()=>Time);

设置状态是异步的,您不能期望更新的状态值正好在
设置状态
之后。要检查更新的值,请使用回调方法。这样写,它将打印更新的值:

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

setState()不会立即改变this.state,但会创建 等待状态转换。调用此命令后访问this.state 方法可能返回现有值。没有 保证对setState的调用和可能发生的调用的同步操作 为提高性能而进行批处理

检查这个答案:

它解释了很多:)。谢谢你。可能有两份