react-navigation之TabNavigator, StackNavigator使用配合redux

我在react-navigation的組件StackNavigator 和TabNavigator組合使用在加上redux,出現如下問題

there is no route defined for key ***must be one of 

這個類似的在 react-navigation的github也有,StackNavigator裏嵌套一個TabNavigator, 


navreducer傳遞 AppNavigations就放入 <Provider>中 render 出來 顯示了

const AppNavigations = ({ dispatch, nav }) => {
	return <Navigator navigation={addNavigationHelpers({ dispatch, state: nav })} />
}
  
const mapStateToProps = state => ({
  nav: state.navreducer,
});

module.exports = connect(mapStateToProps)(AppNavigations);

combineReducers 裏還需要配置navReducer

const allReducers = combineReducers({

	nav: navreducers,
});


那麼navreducers的配置就是重點了, 不注意 就把TabNavigator裏面的route 配置進去了

export const nav = (state, action) => {

    switch (action.type) {
         //TabNavigator 裏模塊
        case '****':
            return Navigator.router.getStateForAction(
                NavigationActions.navigate({ routeName: 'Tabchild' }),
                state
            );
        case '**':
        //TabNavigator 裏模塊
            return Navigator.router.getStateForAction(
                NavigationActions.navigate({ routeName: 'Tabchild' }),
                state
            );
        case 'WebDetail':
            return Navigator.router.getStateForAction(
                NavigationActions.navigate({ routeName: 'WebDetail' }), {...state, webViewURL: action.webViewURL }
            );
        default:
            return Navigator.router.getStateForAction(action, state) || state;

    }
}
上面做是不對的, 這樣做了就報出上面的錯誤,正確如下,因爲我們在給provider 裏提供的就是StackNavigator,這樣就對應了

export const navreducer = (state, action) => {
    switch (action.type) {
        case 'WebDetail':
            return Navigator.router.getStateForAction(
                NavigationActions.navigate({ routeName: 'WebDetail' }), 
                {...state, webViewURL: action.webViewURL }
            );
        default:
            return Navigator.router.getStateForAction(action, state) || state;
    }
}


加上redux的好處,比如,在切換頁面時 就可以直接 dispatch 切換轉跳頁面了, 不然換個 同時吧 參數webURl傳遞給下一個將要展示的頁面 
<TouchableOpacity onPress={()=> {
						
			this.props.navigation.dispatch({ 
				type: 'WebDetail', webViewURL: data.alt 
							});
						}}>
</TouchableOpacity>

webview 需要的參數通過state就能獲取到

class WebView extends Component {
	render() {
		return <WebView source={{uri: this.props.url}}/>
	}
}


function mapStateToProps(state) {
	return {
		url: state.navreducer.webViewURL
	}
}

當然可以用其他的辦法用 navigate 方法切換 傳遞webViewURL

	<TouchableOpacity onPress={()=> {
		this.props.navigation.navigate('WebDetail', webViewURL);
						}}>
				
	</TouchableOpacity>

在 mapStateToProps輸出看 這樣就 得通過很多成了看着也覺得數據隱藏的太深了







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章