路由器状态没有与redux一起保留在react-native中

jsd*_*rio 17 reactjs react-native redux react-redux react-native-router-flux

reduxreact-native使用react-native-router-flux和中有以下配置redux-persist.我想在刷新时检索最后一个当前路由,但是路由堆栈在重新加载时被覆盖.

这是reducers/index.js文件

import { combineReducers, createStore, applyMiddleware, compose } from 'redux'
import { persistStore, autoRehydrate } from 'redux-persist'
import { AsyncStorage } from 'react-native'
import logger from 'redux-logger'

import { startServices } from '../services'
import navigation from './navigation'
import devices from './devices'
import rooms from './rooms'


import { ActionConst } from 'react-native-router-flux'

function routes (state = {scene: {}}, action = {}) {
  switch (action.type) {
    // focus action is dispatched when a new screen comes into focus
    case ActionConst.FOCUS:
      return {
        ...state,
        scene: action.scene,
      };

    // ...other actions

    default:
      return state;
  }
}

export const reducers = combineReducers({
  routes,
  navigation,
  devices,
  rooms
})

const middleware = [logger()]

const store = createStore(
  reducers,
  compose(
    autoRehydrate(),
    applyMiddleware(...middleware)
  )
)

persistStore(store, {storage: AsyncStorage}, function onStoreRehydrate () {
  startServices()
})

export { store, reducers }
Run Code Online (Sandbox Code Playgroud)

编辑:这是index.js它的提供者和场景:

import React, { Component } from 'react'
import { store } from './reducers'
import { Provider, connect } from 'react-redux'
import { Router, Scene, Actions } from 'react-native-router-flux';

import Home from './containers/home'
import Login from './containers/login'
import Device from './containers/device'


const scenes = Actions.create(
  <Scene key="root">
      <Scene key="home" component={Home} />
      <Scene key="login" component={Login} />
      <Scene key="device" component={Device} />
  </Scene>
)

const RouterWithRedux = connect()(Router)

export default class EntryPoint extends Component {
  render () {
    return (
      <Provider store={store}>
        <RouterWithRedux scenes={scenes} />
      </Provider>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*haw 0

react-native-router-flux即使与 redux 一起使用,它本身也不会恢复场景。Redux 仅跟踪状态,因此如果您希望导航状态持续存在,则必须让应用程序在启动时导航到上一个场景。

假设您有 redux 正在使用react-native-router-flux,您所需要做的就是将应用程序的初始组件连接到 redux 以获取状态,然后更改场景以匹配。

因此,在为应用程序加载的初始组件场景中,最后执行类似的操作以访问您的 redux 存储:

const mapStateToProps = (state) => {
  const { nav } = state

  return {
    currentScene: nav.scene.name,
  }
}

INITIAL_COMPONENT = connect(mapStateToProps)(INITIAL_COMPONENT)
Run Code Online (Sandbox Code Playgroud)

然后,在该组件的生命周期方法之一中,您可以像这样重定向:

const { currentScene } = this.props
const initialScene = "Login"

if (currentScene !== initialScene) {
  Actions[currentScene]()
}
Run Code Online (Sandbox Code Playgroud)

您还可以传入导航到最后一个场景时使用的道具,或者在 redux 存储没有持久存在的场景时设置您想要转到的默认场景。我正在开发的应用程序现在可以完美地保持状态。