React Native和Redux:如何为导航创建唯一的路由密钥?

时间:2016-09-09 01:04:17

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

在React Native / Redux项目中,我有一个带有导航按钮的侧边菜单,可以导航到<Home/><Profile/>。如果第一次点击其中任何一个,例如Home按钮,则它会成功导航到<Home/>

如果我点击Profile按钮,它会导航到<Profile/>,但如果我再次点击没有Home按钮导航到<Home/>,我会收到以下内容错误:

enter image description here

那么每次使用Using,NavigationStateUtils时如何用唯一键来推送?或者有更好的方法来处理唯一键?

到处看看并测试了几天但没有运气,所以来到这里寻求帮助!

以下是代码

navReducer.js:

const initialState = {
  index: 0,
  key: 'root',
  routes: [{
   key: 'login',
   title: 'Login',
   component: Login,
   direction: 'horizontal',
  }]
}

function navigationState (state = initialState, action) {
  switch(action.type) {
    case PUSH_ROUTE:
      if (state.routes[state.index].key === (action.route && action.route.key)) return state
    return NavigationStateUtils.push(state, action.route)

    case POP_ROUTE:
      if (state.index === 0 || state.routes.length === 1) return state
      return NavigationStateUtils.pop(state)

   default:
     return state

  }
}

处理导航和使用Home路由的方法,例如:

  _handleNavigate(action) {
    switch (action && action.type) {
      case 'push':
        this.props.pushRoute(action.route)
      default:
        return false
    }
  }

const route = {
  group: {
    type: 'push',
    route: {
      key: 'home',
      title: 'Home',
      component: Home,
      direction: 'horizontal',
    },
  }
}

this._handleNavigate(route)

修改

这是你应该如何按下按钮的路线?

const route = {
  interest: {
    type: 'push',
    route: {
      key: 'profile',
      title: 'Profile',
      component: Profile,
      direction: 'horizontal',
      unique: true,
    }
  }
}

1 个答案:

答案 0 :(得分:1)

对于您的具体情况,基本上您需要在推送后在这些特定路线之间跳转。每次推送Login或Home时,Navigator都希望它是新的路线。但是您的导航堆栈已经有Home和Login路由。 NavigationStateUtils有此方法的jumpTo方法。

在调用push之前,检查路由是否已经存在于堆栈中并进行跳转调用它已经在堆栈中。您可以更改您的navigationState,如下所示:

function navigationState (state = initialState, action) {
 if(action.type == PUSH_ROUTE && action.route.unique==true)
 {
    if(state.routes.find(child => child.key === key))
    {
       return NavigationStateUtils.jumpTo(state, action.route.key)
    }
 }
 switch(action.type) {
    case PUSH_ROUTE:
      if (state.routes[state.index].key === (action.route && action.route.key)) return state
    return NavigationStateUtils.push(state, action.route)

    case POP_ROUTE:
      if (state.index === 0 || state.routes.length === 1) return state
      return NavigationStateUtils.pop(state)

    default:
     return state

  }
}

路线如下:

const initialState = {
  index: 0,
  key: 'root',
  routes: [{
   key: 'login',
   title: 'Login',
   component: Login,
   unique:true,
   direction: 'horizontal',
  }]
}

此外,我认为您的以下if声明将是真实的:

if (state.routes[state.index].key === (action.route && action.route.key)) return state