打开react-native屏幕时调用函数

Fil*_*ahm 3 function react-native react-navigation

每次用户打开我的一个反应原生屏幕时,我都会尝试从AsyncStorage加载JSON(我正在使用StackNavigator).此JSON包含有关我的状态应设置为什么的信息.

如何调用每次打开此屏幕时运行的函数?

更多信息:我编写了一个函数,根据从AsyncStorage加载的JSON更新我的状态.从按钮调用时,该功能完美无缺,但是当调用该功能时render(),我的部分屏幕会冻结,某些按钮不再可触摸.奇怪的是,只有TextInput仍然有效.

div*_*ine 5

使用componentWillMount()方法.这将render()在触发方法之前自动执行.

class Sample extends Component{
    state = {data : []};
    componentWillMount(){
        this.setState({data : inputObject});
    }
    render(){
        return(
            <View>
            //you can render the data here
            </View>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

参考:https://facebook.github.io/react/docs/react-component.html#componentwillmount

  • 该方法被标记为遗留,不应再使用:https://reactjs.org/docs/react-component.html#unsafe_componentwillmount (4认同)