gpt4 book ai didi

javascript - 为什么会出现错误 : 'should not push route with duplicated key' with NavigationStateUtils in React Native?

转载 作者:行者123 更新时间:2023-11-30 15:51:52 25 4
gpt4 key购买 nike

在我的 React Native + Redux 中,我使用 NavigationStateUtils 为导航设置了以下缩减器:

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

然后有一个按钮组件调用导航操作,如下所示:

  _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
}
}

render(){
const route = {
type: 'push',
route: {
key: this.props.navKey,
title: this.props.pageName,
component: this.props.componentName
}
}

return(
<TouchableHighlight onPress={() => this._handleNavigate(route)}>
<Text style={styles}>{pr.pageName}</Text>
</TouchableHighlight>
)

我第一次按下按钮时,它导航正确并且没有错误。但是当我再次按下按钮时,出现以下错误:should not push route with duplicated key

我如何使用 NavigationStateUtils 解决我在 reducer 中实现的问题?

提前致谢!

最佳答案

您必须修改 reducer 以进行推送。你需要做的是——

  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);

关于javascript - 为什么会出现错误 : 'should not push route with duplicated key' with NavigationStateUtils in React Native?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39199007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com