使用`react-navigation`导航时如何触发render()方法?

Posted

技术标签:

【中文标题】使用`react-navigation`导航时如何触发render()方法?【英文标题】:How to trigger render() method when navigating back with `react-navigation`? 【发布时间】:2018-01-13 08:54:27 【问题描述】:

我有一个简单的应用程序,在 StackNavigator 内有两个屏幕:

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

按下按钮后,应用导航到ChooseColorPage

class MainPage extends Component 

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

然后,用户可以通过按下按钮来选择颜色,这会触发导航回MainPage

class ChooseColorPage extends Component 

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

我希望MainPage 根据所选颜色进行更新,但是在返回导航时不会调用render() 方法

问题:在react-navigation屏幕之间导航时,在哪些情况下会调用render()方法?

我会假设更新ColorReducer 中的状态足以触发MainPage 中的render() 调用,但这不会发生。

【问题讨论】:

【参考方案1】:

原来这不是导航问题,而是状态管理问题。

我在我的主页上错误地设置了mapStateToProps。添加后,导航更新会调用render()

我的应用程序缩减器:

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

我的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;
    
;

我的mapStateToProps

const mapStateToProps = state => 
    return  colorKey: state.color.colorKey ;
;

【讨论】:

以上是关于使用`react-navigation`导航时如何触发render()方法?的主要内容,如果未能解决你的问题,请参考以下文章