我为我的React Native项目设置了Redux。以下是我的导航缩减器(navReducer.js
):
import { PUSH_ROUTE, POP_ROUTE } from '../Constants/ActionTypes'
import { NavigationExperimental } from 'react-native'
import Login from '../Components/Login'
const {
StateUtils: NavigationStateUtils
} = NavigationExperimental
const initialState = {
index: 0,
key: 'root',
routes: [{
key: 'login',
title: 'Login',
component: Login
}]
}
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
}
}
export default navigationState
在我的根组件(NavRoot.js
)中,操作用以下方式处理:
_handleBackAction() {
if (this.props.navigation.index === 0) {
return false
}
this.props.popRoute()
return true
}
_handleNavigate(action) {
switch (action && action.type) {
case 'push':
this.props.pushRoute(action.route)
return true
case 'back':
case 'pop':
return this._handleBackAction()
default:
return false
}
}
由按钮(NavButton.js
)触发:
_navigate(route){
this.props._handleNavigate(route)
}
render(){
const route = {
type: 'push',
route: {
key: this.props.navKey,
title: this.props.pageName,
component: this.props.componentName
}
}
return(
<TouchableHighlight onPress={() => this._navigate(route)}>
<Text style={styles}>{pr.pageName}</Text>
</TouchableHighlight>
)
第一次按下按钮(NavButton.js
)时,它会正确导航。但是当再次按下时,我收到以下错误:should not push route with duplicated key /*'route.key: this.props.navKey' in this case*/
。
所有似乎都有道理,但可能是什么问题?
提前谢谢!
答案 0 :(得分:1)
不应推送带有重复密钥的路由
key
属性必须是唯一的。
如果您需要使用相同的key
创建多个场景,则可以将scene
属性传递给reducer,并增加key
值......
function navigation(state = guestState, action) {
const { index, routes } = state
switch (action.type) {
case NAV_PUSH: {
const nextIndex = index + 1
const newState = {
...action.state,
key: `${action.state.scene}_${nextIndex}`,
}
return {
...state,
index: nextIndex,
routes: [
...routes,
newState,
],
}
}
...
}
答案 1 :(得分:0)
您可以检查输入是否在导航减速器中连续出现:
case 'PUSH_ROUTE':
if (state.routes[state.index].key === (action.route && action.route.key)) return state
if ((state.routes.length && state.routes[state.routes.length-1].key) === (action.route && action.route.key)) return state
return NavigationStateUtils.push(state, action.route)