Search code examples
react-nativedynamicreact-lifecycle

React Native - Rerunning the render method


I have a file here that defines an icon for the title.

    static navigationOptions = ({ navigation }) => {
        return {
            headerRight: () => (<HomeHeaderIcon/>)
        }
    };

HomeHeaderIcon.js

export default class HomeHeaderIcon extends Component {
    async componentDidMount(){
        const token = await AsyncStorage.getItem('token');
        this.setState({token});
    }
    state={
        token:null
    };

    render() {
        return (
            <View>
                {
                    this.state.token ===null
                        ?
                        (
                            <TouchableOpacity
                                onPress={() => (NavigationService.navigate("LogStack"))}>
                                <Icon name="ios-power" size={30} style={{color: "white",marginRight:wp("5%")}}/>
                            </TouchableOpacity>
                        )
                        :
                        (
                            <TouchableOpacity
                                onPress={() => (NavigationService.navigate("Profile"))}>
                                <Icon name="ios-home" size={30} style={{color: "white",marginRight:wp("5%")}}/>
                            </TouchableOpacity>)
                }
            </View>
        );
    }
}

The system works exactly as I want. If there is a token, I say icon1 or icon2 show. The problem is I do this in componentDidMount, the icon does not change without refreshing the page. How do I render it again?


Solution

  • componentDidMount is called, as the name suggests, just once, when the component is mounted. Use componentDidUpdate to decide how your component behaves based on what piece of props or state has changed.

    Read the documentation for more information regarding lifecycle methods.