React Navigation,Redux,如何更改屏幕?

时间:2018-03-10 18:27:56

标签: react-native redux react-redux react-navigation

我的路线没有使用最新的React Navigation v1.5.0触发屏幕更改。

我已在我的设置中集成了Redux,详见react-navigation-redux docs。我在这里看到的最大变化是'addListener'设置,虽然我不确定这是阻止屏幕更改的原因。我的路线使用v.1.0正常工作。

我看到导航操作被触发,屏幕被添加到调试器中的导航状态,但屏幕没有改变。

单击下面的按钮调度操作,但屏幕不会更改为“关于”屏幕并保持在主屏幕上。

RootNav

StackNavigator
  - Home
  - About

Index.js

const middleware = createReactNavigationReduxMiddleware(
  "root",
  state => state.navigationState,
)

const addListener = createReduxBoundAddListener("root");

class App extends Component {
  render () {
    return (
      <View>
        <RootNav navigation={addNavigationHelpers({
         dispatch: this.props.dispatch,
         state: this.props.navigationState,
         addListener,
         })} />
     </View>
    )
  }
}

按钮

<TouchableHighlight onPress={ () => 
   this.props.dispatch(NavigationActions.navigate({
     routeName: 'About'
   })) }>
  <Text>About</Text>
</TouchableHighlight>

点击按钮后的状态:

nav: {
  key: StackRouterRoot,
  index: 1,
  isTransitioning: true,
  routes: [
   0: {routeName: 'Home'},
   1: {routeName: 'About'},
  ],
}

您如何正确调度路线/屏幕更改?

1 个答案:

答案 0 :(得分:0)

考虑到您正在使用navigation stateredux-navigation未与redux绑定。您需要创建Navigation reducer并将其绑定到store

例如

// Nav.js
// This is your exported router, which gets the initial State
import AppNavigator from '../Navigation/AppNavigation'
const initialState = AppNavigator.router.getStateForAction(AppNavigator.router.getActionForPathAndParams('LaunchScreen'))

export default reducer = (state = initialState, action) => {
  const newState = AppNavigator.router.getStateForAction(action, state)
  return newState || state
}

并将其绑定到您的商店

// Store.js
    const RootReducer = combineReducers(config, {
  nav: Nav,
  // ...other reducers
});

最后在您的Redux Navigation状态中将其用作

function ReduxNavigation (props) {
  const addListener = createReduxBoundAddListener('root')
  const { dispatch, nav } = props
  const navigation = ReactNavigation.addNavigationHelpers({
    dispatch,
    state: nav, // this is bound to redux store using mapStateToProps
    addListener
  })

  return <AppNavigation navigation={navigation} />
}

const mapStateToProps = state => ({ nav: state.nav })
export default connect(mapStateToProps)(ReduxNavigation)

docs

中所述