Home How to trigger render() method when navigating back with `react-navigation`?
Reply: 1

How to trigger render() method when navigating back with `react-navigation`?

bizz84
1#
bizz84 Published in 2018-01-13 08:54:27Z

I have a simple app with two screens inside a StackNavigator:

export const AppNavigator = StackNavigator({
    Main: { screen: MainPage },
    ChooseColor: { screen: ChooseColorPage }
}, {
    initialRouteName: 'Main',
});

Upon pressing a button, the app navigates to ChooseColorPage:

class MainPage extends Component {

    onChooseColor() {
        const { navigation } = this.props;
        navigation.navigate('ChooseColor', {});
    }
}

Then, the user can choose a color by pressing a button, which triggers a navigation back to the MainPage:

class ChooseColorPage extends Component {

    onSelectColor(colorKey) {
        // this updates the state inside a `ColorReducer`
        this.props.colorChanged({ colorKey });
        const { navigation } = this.props;
        navigation.goBack();
    }
}

I want the MainPage to update based on the chosen color, however the render() method is not called on back navigation.

Question: Under which cases is the render() method called when navigating between screens with react-navigation?

I would have assumed that updating the state in the ColorReducer would have been enough to trigger a render() call in MainPage but this does not happen.

bizz84
2#
bizz84 Reply to 2018-01-13 09:54:53Z

Turns out this is not a navigation problem, but a state management problem.

I was incorrectly setting up mapStateToProps on my MainPage. After adding this, render() is called as a result of a navigation update.

My app reducer:

const AppReducer = combineReducers({
  color: ColorReducer,
  nav: NavReducer,
});

My ColorReducer:

const initialState = {
    colorKey: null,
};

const ColorReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'COLOR_CHANGED':
            return { ...state, colorKey: action.payload.colorKey };
        default:
            return state;
    }
};

My mapStateToProps:

const mapStateToProps = state => {
    return { colorKey: state.color.colorKey };
};
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.331954 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO