为什么会出现错误:'不应该使用React Native中的NavigationStateUtils推送具有重复密钥的路由?

时间:2016-08-29 05:26:23

标签: javascript reactjs react-native redux react-jsx

在我的React Native + Redux中,我使用NavigationStateUtils设置了以下reducer用于导航: 从'../Constants/ActionTypes'导入{PUSH_ROUTE,POP_ROUTE} 从'react-native'导入{NavigationExperimental} 从'../Components/Login'登录 const {   StateUtils:NavigationStateUtils } = NavigationExperimental const initialState = {   指数:0,   key:'root',   路线:[{    key:'login',    标题:'登录',    组件:登录   }] } function navigationState(state = initialState,action){   switch(action.type){     案例PUSH_ROUTE:       if(state.routes [state.index] .key ===(action.route&& action.route.key))return state     return NavigationStateUtils.push(state,action.route)     案例POP_ROUTE:       if(state.index === 0 || state.routes.length === 1)返回状态       return NavigationStateUtils.pop(state)    默认:      返回状态   } } 导出默认的navigationState 并得到一个按钮组件,调用导航操作,如下所示:   _handleBackAction(){     if(this.props.navigation.index === 0){       返回false     }     this.props.popRoute()     返回true   }   _handleNavigate(action){     switch(action&& action.type){       案例'推':         this.props.pushRoute(action.route)         返回true       案件'回':       案例'pop':         return this._handleBackAction()       默认:         返回false     }   }   渲染(){     const route = {       类型:'推',       路线:{         key:this.props.navKey,         title:this.props.pageName,         component:this.props.componentName       }     }     返回(       < TouchableHighlight onPress = {()=> this._handleNavigate(路线)}>         <文字样式= {styles}> {pr.pageName}< / Text>       < / TouchableHighlight>     ) 我第一次按下按钮,它正确导航,没有错误。但是当我再次按下按钮时,我收到以下错误:不应该使用重复键推送路由。 我如何使用NavigationStateUtils解决我在reducer中实现的问题? 先感谢您!

1 个答案:

答案 0 :(得分:2)

您必须修改您的减速器才能进行推送。你需要做的是 -

  1. 检查您必须推送的关键路线是否已存在于堆栈中。
  2. 如果它没有在堆栈中推送该路由
  3. 如果已经存在,则找到其索引并复制现有状态,但不包含该重复路由。
  4. 现在你所要做的就是用克隆状态更新你的状态。

     case PUSH_ROUTE:{
    
          // trying to push the route where we already are, no need to change a thing
              if (state.routes[state.index].key === (action.route && action.route.key)) 
                 return state;
          // ensure no duplicate keys
              const index = state.routes.findIndex((route) => {
              return action.route.key === route.key && action.route.title ===route.title;
             });
              if (index > -1) {
                       const clonedState = Object.assign({}, state);
                       clonedState.routes.splice(index, 1);
                       return NavigationStateUtils.push(clonedState, action.route);
                       }
           // normal case for a push
                 return NavigationStateUtils.push(state, action.route);
    

    }